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?
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.)
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With