Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: fit relative positioned parent to height of absolute positioned child

Tags:

I am trying to build a simple slideshow. So far, the basic markup looks like this:

<h1>My Slideshow</h1>

<p>This paragraph behaves as expected.</p>

<div class="slide-container">
  <div class="slide">
    <h2>First Slide</h2>
    <p>Some stuff on this slide…</p>
  </div>

  <div class="slide">
    <h2>Second Slide</h2>
    <p>And some more stuff here…</p>
  </div>
</div>

<p>This paragraph will disappear beneath the stacked images.</p>

This is the corresponding CSS:

.slide-container {
  position: relative;
}

.slide {
  position: absolute;
  top: 0;

  /* just for the looks */
  width: 20em;
  padding: 0 1em;
  border: 1px solid steelblue;
  background: white;
}

The problem is, that the .slide-container does not fit to the height of its child (or children) .slide (see screenshot).

enter image description here

I know i can set the height of the .slide-container manually, but i want to put this in a fluid grid, where the height is variable. Is there any way to achieve this?

like image 647
Patrick Oscity Avatar asked Dec 20 '11 14:12

Patrick Oscity


2 Answers

Absolutely-positioned items are logically-associated with their parent, but not "physically". They're not part of the layout, so the parent item can't really see how big they are. You need to code the size yourself, or sniff it with JavaScript and set it at run-time.

like image 50
Diodeus - James MacFarlane Avatar answered Sep 19 '22 14:09

Diodeus - James MacFarlane


You can use this using jquery:

    function sliderheight(){
        divHeight = $('.slide').height();
        $('.slide-container').css({'height' : divHeight});
    }
    sliderheight();

This will resize the 'slide-container' div to have the same height as the 'slide' div.

You can make it responsive by calling the function on the firing of a 'resize' event:

   $(window).resize(sliderheight);

Hope this helps.

like image 31
Charlie Tupman Avatar answered Sep 21 '22 14:09

Charlie Tupman