CSS - position: absolute; - auto height

I recently had this problem with a fade in/out CSS transition slideshow, and ended up solving it by giving the first child element position: relative; and the others position: absolute; top:0; left: 0; which ensures that the containers height is the same as the height of first element. Since my CSS transition slideshow uses the opacity property the container dimensions never changes during the course of the slideshow.

Alas, since I also needed to supply a javascript fallback for older browsers I had to set the container height for these browsers anyway (because of jQuerys fadeIn/fadeOut actually setting display: none; I would guess).


Here is a long overdue cross-browser solution to your problem. No more static width, no more em hack.

<style>
  /* clearfix */
  .container:after {
    content: '';
    display: table;
    clear: left;
  }

  .page {
    float: left; /* display side-by-side */
    width: 100%; /* be as wide as parent */
    margin-right: -100%; /* take up no width */
  }
</style>

<div class="container">
  <div class="page"></div>
  <div class="page"></div>
</div>

After searching for a solution to this problem for so long, I am baffled to see how simple it is. Granted, the .page elements are not absolutely positioned. However, all the same goals can be achieved through this method, with almost no pain or sacrifice.

Here's a demo: https://jsfiddle.net/eqe2muhv/

This also works for inline-blocks, of course. Though you might need to set the font-size or letter-spacing of the container to 0. I would also recommend using vertical-align: top on the .page, to simulate a regular block element.

Here's a demo: https://jsfiddle.net/dzouxurs/8/


As far as I know, there's no way for absolutely positioned child elements to affect the height of their statically, or relatively positioned parent elements using only CSS. Either:

  • Reorganize so that the child elements remain in the document flow
  • Use JavaScript on load of the page to set the height of the parent to the height of the largest child

This issue is common in fade-in/fade-out JavaScript slideshows, and from what I've seen either 1) the height of the parent container needs to be defined or 2) the parent container's height is set dynamically for each slide.

Tags:

Css