简体   繁体   English

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

[英]how to align one div top and another bottom withing container div?

Seems the bottom div is aligned bottom to the page but not to the container div. 底部div似乎与页面底部对齐,而不与容器div对齐。 I need to align the bottom one to the bottom of the container DIV. 我需要将底部的一个与容器DIV的底部对齐。

Code: 码:

 #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> 

在此处输入图片说明

Simply give your #container position:relative; 只需给出您的#container position:relative;

 #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; } 
 <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> 

Alternatively you could go with flexbox : 或者,您可以使用flexbox

 #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 */ } 
 <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> 

You're almost there, #container has to be position: relative; #container#container必须处于position: relative;

Absolute is always to the closest relative element. 绝对始终是最接近的相对元素。 In this case you have no relative elements, so it will default to body . 在这种情况下,您没有相对元素,因此它将默认为body By giving #container the relative value, #bottom will be positioned relative to #container 通过为#container相对值, #bottom对于#container定位

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

All you need to set its parent position:relative then it will consider its body. 您只需设置其父position:relative ,便会考虑其主体。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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