Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand div to contain absolutely positioned content

I have a div that contains a bunch of absolutely positioned controls. These controls are dynamically generated and I want the div to expand so it will cover all the content in both width an height. How can I do this in CSS?

like image 943
mrK Avatar asked Aug 29 '12 16:08

mrK


People also ask

How would you absolutely positioned element?

An absolutely positioned element is an element whose computed position value is absolute or fixed . The top , right , bottom , and left properties specify offsets from the edges of the element's containing block. (The containing block is the ancestor relative to which the element is positioned.)

Can a div be position absolute and relative?

Clearly, nothing can be absolute and relative at the same time. Either you want the element to position itself based on another ancestor's position or based on the page flow.


2 Answers

This is possible with CSS grid:

.container {
  display: grid;
}

.container > * {
  grid-area: 1/1;
}

.child {
  /* Instead of using top/left, use margins: */
  margin-top: 10px;
  margin-left: 50px;
}

This creates a grid that only has one cell, and every child goes into that cell.

The layout of one child doesn't impact the others, they just overlay on top of one another, but the grid (.container) will expand to fit the bounds of all children.

Demo: https://codepen.io/jaffathecake/pen/zWrvZx

like image 119
JaffaTheCake Avatar answered Oct 17 '22 12:10

JaffaTheCake


That is difficult to achieve. When you have a relative parent with absolute children inside, they can not affect the size of the parent div.

You have to use relative children also. Why are the controls positioned absolute?

But where CSS fails, JavaScript comes to the rescue. So this can be solved.

like image 20
Christian Jørgensen Avatar answered Oct 17 '22 11:10

Christian Jørgensen