且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

子div不扩展到父div

更新时间:2023-02-07 18:44:10

高度不符合您预期的方式.当您指定 height:100%时,该百分比是通过查找指定高度为 absolute relative 定位.

height doesn't behave the way you seem to be anticipating. When you specify height: 100% that percentage is calculated by looking up the DOM for the first parent of said element with a height specified that has absolute or relative positioning.

当涉及到身体标签时,您可以作弊,因此,如果您有这样的事情:

You can cheat when it comes to the body tag, so if you had something like this:

<body>
  <div style="height: 100%">
  </div>
</body>

某些浏览器/版本将通过占用页面的总高度来达到您期望的方式.但是,如果您不进行任何深入的研究,它将无法正常工作.

Some browsers/versions will behave the way you expect by taking up the total height of the page. But it won't work when you go any deeper than that.

这是我用来将div拉到页面底部的方法,它涉及绝对定位(关于这一点的妙处是它非常符合跨浏览器的要求,不需要JavaScript即可实现):

Here is the approach I use to strech a div to the bottom of the page, it involves absolute positioning (nice thing about this one is that it is pretty cross-browser compliant and doesn't require javascript to pull it off):

<div id="parent">
   <div id="childNorm"></div>
   <div id="childStrech"></div>
</div>



#parent
  {
      position: absolute;
      width: 1000px;
      bottom: 0;
      top: 0;
      margin: auto;
      background-color: black;
  }

  #childNorm
  {
     position: absolute;
     width: 1000px;
     top: 0;
     height: 50px;
     background-color: blue;
     color: white;
  }

  #childStrech
  {
     position: absolute;
     width: 1000px;
     top: 50px;
     bottom: 0;
     background-color: red;
     color: white;
  }

以下是用于演示的Jsfiddle: http://jsfiddle.net/t7ZpX/

Here is a Jsfiddle for demo: http://jsfiddle.net/t7ZpX/

诀窍:

当您指定绝对位置然后放入 bottom:0; 时,该元素将延伸到页面底部;您只需要担心将元素定位为折衷.

When you specify absolute positioning and then put in bottom: 0; that causes the element to stretch to the bottom of the page; You just have to worry about positioning the elements as a trade off.