How can I make elements with position:absolute
and dynamic height occupy vertical space using only css? Is there any trick with containers and display that I can use?
To center an element both vertically and horizontally: position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; But if you would like to understand how I came to these solutions, read further for more explanation.
Unfortunately, using absolute positioning means, by definition, that your element is no longer taking up space.
Absolutely positioned elements are removed entirely from the document flow. That means they have no effect at all on their parent element or on the elements that occur after them in the source code. An absolutely positioned element will therefore overlap other content unless you take action to prevent it.
If you want to center something horizontally in CSS you can do it just by, using the text-align: center; (when working with inline elements) or margin: 0 auto; (when working with block element).
Unfortunately, using absolute positioning means, by definition, that your element is no longer taking up space. So no, only through css there is no way to do this.
You can of course use jQuery (or plain javascript) to accomplish this. How I'd do it is have a space
element next to each vertical element. Enclose both the space element and the absolutely positioned vertical element in a relatively positioned div. On page load, change the height of the space element to match the height of the vertical element.
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