Daniel
Daniel

Reputation: 1601

Adapt parent to maximum size of it's children in CSS

Is it possible to make parent div adjust it's height to max of it's children height and width to max width of it's children width?

* { box-sizing: content-box; }

.parent {
  position: relative;
  
  border: 2px solid blue;
  
  height: max-content;
  width: max-content;
}

.child-a {
  position: relative;
  background: rgba(255, 0, 0, 0.3);
  
  width: 135px;
  height: 100px;
  
  top: 0;
  left: 0;
}

.child-b {
  position: absolute;
  background: rgba(0, 255, 0, 0.3);
  
  width: 100px;
  height: 135px;
  
  top: 0;
  left: 0;
}
<div class='parent'>
  <div class='child-a' />
  <div class='child-b' />
</div>

I tried various combinations of position, top, left attributes in the example above.

wanted parent layout

Maybe it is possible to achieve this effect at least in one dimension?

Upvotes: 3

Views: 2052

Answers (3)

Temani Afif
Temani Afif

Reputation: 273807

A simple float can do this if you want better support than CSS grid

* { box-sizing: content-box; }

.parent {
  display:inline-block; /* This */
  border: 2px solid blue;
}

.child-a {
  background: rgba(255, 0, 0, 0.3);
  float:left; /* and this */
  width: 135px;
  height: 100px;
}

.child-b {
  background: rgba(0, 255, 0, 0.3);
  width: 100px;
  height: 135px;
}

/* To illustrate that it works whataver the width/height */
.parent:hover .child-b{
  width:180px;
}
.parent:hover .child-a{
  height:180px;
}
<div class='parent'>
  <div class='child-a' ></div>
  <div class='child-b' ></div>  
</div>

Upvotes: 1

Saran
Saran

Reputation: 1575

Yes, we can achieve this via CSS grid.

* { box-sizing: content-box; }

.parent {
  display: grid;
  grid-template-areas: "grid-overlap";
  border: 2px solid blue;
  height: auto;
  width: max-content;
}

.child-a {
  grid-area: grid-overlap;
  background: rgba(255, 0, 0, 0.3);
  width: 135px;
  height: 100px;
  overflow: overlay; 

}

.child-b {
  grid-area: grid-overlap;
  background: rgba(0, 255, 0, 0.3);
  width: 100px;
  height: 135px;
}
<div class='parent'>
  <div class='child-a'></div>
  <div class='child-b'></div>
</div>

Upvotes: 0

Paulie_D
Paulie_D

Reputation: 115289

Yes, this is possible without position:absolute using CSS-Grid and layering the elements in the same grid cell.

* {
  box-sizing: content-box;
}

.parent {
  position: relative;
  border: 2px solid blue;
  height: max-content;
  width: max-content;
  display: grid;
}

.child-a {
  position: relative;
  background: rgba(255, 0, 0, 0.3);
  width: 135px;
  height: 100px;
  grid-column: 1 / -1;
  grid-row: 1;
}

.child-b {
  background: rgba(0, 255, 0, 0.3);
  width: 100px;
  height: 135px;
  grid-column: 1 / -1;
  grid-row: 1
}
<div class='parent'>
  <div class='child-a'></div>
  <div class='child-b'></div>
</div>

Upvotes: 3

Related Questions