如何使用容器div对齐一个div顶部和另一个底部?

时间:2017-03-03 20:13:04

标签: javascript html css

似乎底部div与页面底部对齐,但不与容器div对齐。我需要将底部对齐到容器DIV的底部。

代码:



#container {
  border: 1px solid red;
  height: 300px;
}

#top {
  border: 2px solid red;
  display: inline-block;
  vertical-align: top;
  position: absolute;
  top: 0;
}

#bottom {
  border: 2px solid red;
  vertical-align: bottom;
  width: 100px;
  position: absolute;
  bottom: 0;
}

<div id="container">
  <div id="top">
    test<br /> test
    <br /> test
    <br /><br /> test test test test<br />
  </div>
  <div id="bottom">bottom</div>
</div>
&#13;
&#13;
&#13;

enter image description here

3 个答案:

答案 0 :(得分:2)

只需提供#container position:relative;

即可

&#13;
&#13;
#container {
  border: 1px solid red;
  height: 300px;
  position: relative;
}

#top {
  border: 2px solid red;
  position: absolute;
  top: 0;
}

#bottom {
  border: 2px solid red;
  width: 100px;
  position: absolute;
  bottom: 0;
}
&#13;
<div id="container">
  <div id="top">
    test<br /> test
    <br /> test
    <br /><br /> test test test test<br />
  </div>
  <div id="bottom">bottom</div>
</div>
&#13;
&#13;
&#13;

或者您可以使用 flexbox

&#13;
&#13;
#container {
  border: 1px solid red;
  height: 300px;
  position:relative;
  display: flex;     /* add this */
}

#top {
  border: 2px solid red;
  position: absolute;
  top: 0;
}

#bottom {
  border: 2px solid red;
  width: 100px;
  align-self: flex-end; /* and this */
}
&#13;
<div id="container">
  <div id="top">
    test<br /> test
    <br /> test
    <br /><br /> test test test test<br />
  </div>
  <div id="bottom">bottom</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

你几乎就在那里,#container必须是position: relative;

绝对总是最接近的相对元素。在这种情况下,您没有相关元素,因此默认为body。通过提供#container相对值,#bottom相对定位到#container

#container {
  position: relative;
  border: 1px solid red;
  height: 300px;
}

答案 2 :(得分:1)

您需要设置其父position:relative然后它将考虑其正文。

 #container {
        border: 1px solid red;
        height:300px;
        position:relaive;
    }