How can I make elements with position:absolute
and dynamic height occupy vertical space using only css? Is there any trick with containers and disp
This doesn't apply to all situations, but: if the position: absolute
element has a fixed aspect ratio (e.g. an image or video resizing responsively with height: auto
), you can take advantage of the padding-bottom trick to give a spacer element that same aspect ratio, so that it resizes in tandem with the absolute
element:
.spacer {
height: 0;
padding-bottom: 125%; /* for a 1.25 height/width ratio */
}
You can read the link, but this works because padding-bottom
with a percentage is interpreted as a percentage of the element's width.
It's then up to your particular layout to position the spacer such that it precisely covers or underlays the position: absolute
element, and takes up the space that your absolute
element would have were it not absolute
.