[英]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.