在一个百分比高度的 div 中垂直居中一个 div,是否可能?
在一个百分比高度的 div 中垂直居中一个 div,是否可能?
这个问题已经在这里以及整个互联网上被问了很多次。
快速搜索会带给你大量的结果。不过,我个人偏好的方法是使用display: table-cell;
和vertical-align: middle;
。参见这个页面的示例。(请注意,这在Internet Explorer 6上无法工作。)
.outerdiv{
position: relative; // Or absolute, or fixed
height: 80%;
}
.innerdiv{
position: absolute;
width: 100px;
height: 100px;
top: 50%; // It's at 50%, but not really centered
margin-top: -50px; // So just move it up by the half of its height :D
}
我并不太喜欢这个解决方案,我相信还有很多其他可能性(比如使用表格或 display: table-cell;
)- 但这是我首先想到的...
.outerdiv {
display: table-cell;
vertical-align: middle;
}
警告 - 这并不适用于所有浏览器!
不需要使用px单位。
将top
,bottom
,right
,left
改为百分比:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div style="position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
text-align: center;
white-space: nowrap;
overflow: hidden;">
<div style="position: relative;
display: inline-block;
height: 100%;
vertical-align: middle;"></div>
<div style="background-color: #FEEF88;
position: relative;
display: inline-block;
vertical-align: middle;">Hola todo el mundo :D</div>
</div>
</body>
</html>
我喜欢使用以下技术,其中包含两个容器:
display: table;
display: table-cell;
vertical-align: middle;
display: inline-block;
您可以将任何内容添加到内容框中,而不用担心其宽度或高度!
此外,您可以通过在内部容器中添加 text-align:center;
轻松添加水平居中。
body {
margin : 0;
}
.outer-container {
position : absolute;
display: table;
width: 100%;
height: 100%;
background: #ccc;
}
.inner-container {
display: table-cell;
vertical-align: middle;
}
.centered-content {
display: inline-block;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
Malcolm in the Middle
</div>
</div>
</div>