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

扶醉桌前 提交于 2019-12-19 05:08:48

问题


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).

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?


回答1:


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.




回答2:


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.




回答3:


Perfect way of doing this is to set the relative parent's dimensions i.e. height & width to fit the absolute children.


http://learn.shayhowe.com/advanced-html-css/detailed-css-positioning/

This guy wrote enough to understand the basics of css positioning. Actually the relative parent is used to position all its absolute child logically. But it does not share the physical position as a result it does not stretch itself to cover the relative children.



来源:https://stackoverflow.com/questions/8577090/css-fit-relative-positioned-parent-to-height-of-absolute-positioned-child

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!