2017-03-03 158 views
0

似乎底部div對齊頁面底部,但不是容器div。我需要將底部對齊到容器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>

enter image description here

回答

1

就快,#container必須position: relative;

絕對是永遠的近親元素。在這種情況下,您沒有相關的元素,所以它將默認爲body。通過給#container相對值,#bottom將定位相對#container

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

,只需提供您的#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>

另外,您可以用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>

1

所有你需要設置它的父position:relative則其會考慮它的身體。

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