[英]Vertical align middle div inside div
檢查此HTML:
<div class="wrapper">
<div class="content">
</div>
</div>
<div class="footer">
<hr />
<p>some text</p>
</div>
和CSS:
.footer {
position: absolute;
height: 100px;
width: 100%;
bottom: 0;
background-color: black;
}
.wrapper {
padding-bottom: 100px;
background-color: blue;
height: 100%;
}
.content {
width: 200px;
height: 100px;
margin: auto;
background-color: green;
}
html, body {
width: 100%;
height: 100%;
}
您會看到footer
位置是絕對的,並停留在頁面底部。 wrapper
將覆蓋剩余空間並在其中包含content
。 我想在不破壞當前布局的情況下垂直對齊content
。 你有什么建議嗎?
這是JSFiddle鏈接。 (注意:jsfiddle無法正常工作, footer
下方始終有一個空格,在瀏覽器中運行HTML文件時不會發生此行為)。
注意:我不想使用固定高度的wrapper
,我希望它覆蓋所有剩余空間,所以請不要建議我使用line-height
注意我希望布局易於修改(例如在頂部添加標題或內容)而不破壞它,因此我想避免在wrapper
和content
上使用絕對位置
注意2:很抱歉,我們並沒有明確說明content
大小是固定的,它的大小取決於其中的內容,因此使用negative margin
的解決方案不起作用,如上所述
這是使用以下CSS的一種方法:
.footer {
position: absolute;
height: 100px;
width: 100%;
bottom: 0;
background-color: black;
}
.wrapper {
background-color: blue;
position: absolute;
top: 0;
bottom: 100px;
left: 0;
right: 0;
}
.content {
width: 200px;
height: 100px;
background-color: green;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -100px;
}
html, body {
width: 100%;
height: 100%;
margin: 0;
}
使用絕對定位,然后使用負邊距,因為您的內容具有明確定義的尺寸,所以這相對簡單。
參見演示: http : //jsfiddle.net/audetwebdesign/DgUV2/
對於.wrapper
,請使用頂部,底部,左側和右側偏移量將div拉伸到整個寬度和高度,並考慮到頁腳的100px。
對於.content
,將頂部和左側設置為.wrapper
的中心點的50%,然后使用負邊距調整.content
div的中心。
切記將body
的邊距清零,否則可能會看到10px的空白,具體取決於您的瀏覽器。
我添加了以下內容:
.content {
width: 200px;
height: 100px;
margin: auto;
background-color: green;
/* THE BELOW WAS ADDED */
position: absolute;
top: 50%;
left: 50%;
margin: -100px 0 0 -100px;
}
html, body {
width: 100%;
height: 100%;
/* BELOW ADDED TO REMOVE EXTRA SPACE AROUND EDGES */
margin: 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.