Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

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?

like image 664
Daniel Avatar asked Dec 05 '25 17:12

Daniel


1 Answers

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>
like image 108
Paulie_D Avatar answered Dec 07 '25 07:12

Paulie_D