简体   繁体   中英

Wrapping multiple superimposed divs

TLDR: How do get a container to wrap multiple superimposed fluid-height divs?

I have a div with some objects:

<div class="container">
  <div class="a" style="height: 300px;">Tab page a</div>
  <div class="b" style="height: 100px; display: none;">Tab page b</div>
  <div class="c" style="height: 200px; display: none;">Tab page c</div>
  ...
</div>

Based on a user action, I want to fade b in as a fades out (ie crossfade them). This requires them both being aligned to the top-left corner of container . Normally, I'd just use position: absolute; with the defaults top: 0; and left: 0; to superimpose them. The problem with this is that then the container collapses to 0px tall (rather than the height of its contents, which I want), as a and b have been removed from the flow.

Ok, so I can't user absolute positioning on a and b . How else can I get them to overlap? A negative margin-top also won't work since I don't know the heights of the children (they can change dynamically based on their content), and there could be any number of them.

Is this even possible without JS? If it isn't, what's the least hacky way that doesn't assume A) a small number of children in container or B) the children are a fixed size (known ahead of time or otherwise).

If you know the dimensions of your cross-fading elements, your best bet is to set the height and width of your container element, either through CSS if you only need one width/height, or through javascript if you'd like the container to adapt to new dimensions on cross-fade.

The Javascript method I described can be seen in action here: http://jsfiddle.net/mkd9s/2/

The important part is:

// Get Heights
var aHeight = $('.a').height(),
    bHeight = $('.b').height();

// Set Height on Load
$('.container').height( aHeight );

// Fade on Click
$('.fade').on('click', function(event) {
    event.preventDefault();
    $('.a').fadeOut("slow");
    $('.b').fadeIn("slow");
    $('.container').animate({ height: bHeight });
});

Which first sets the height of the container, then animates the height of the container to be the height of the second element when a button is clicked.

Note that this will rapidly become unwieldy if you've got more than 2 elements in the container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM