如何在另一个<div>中水平居中一个<div>?我成功地使用了被接受答案中的样式来水平居中。我如何垂直居中它?内部的<div>高度是未知的。
如何在另一个<div>中水平居中一个<div>?我成功地使用了被接受答案中的样式来水平居中。我如何垂直居中它?内部的<div>高度是未知的。
来自:http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Universal vertical center with CSS</title>
<style>
.greenBorder {border: 1px solid green;} /* just borders to see it */
</style>
</head>
<body>
<div class="greenBorder" style="display: table; height: 400px; #position: relative; overflow: hidden;">
<div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
<div class="greenBorder" style=" #position: relative; #top: -50%">
any text<br>
any height<br>
any content, for example generated from DB<br>
everything is vertically centered
</div>
</div>
</div>
</body>
</html>
这是一种将盒子垂直和水平居中的酷炫技巧:
display: table;
display: table-cell;
vertical-align: middle;
text-align: center;
display: inline-block;
text-align:left;
或者text-align:right;
这种技巧的优雅之处在于,您可以将内容添加到内容盒子中,而无需担心其高度或宽度!
只需将您的内容添加到内容盒子即可。
body {
margin : 0;
}
.outer-container {
position : absolute;
display: table;
width: 100%; /* This could be ANY width */
height: 100%; /* This could be ANY height */
background: #ccc;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
text-align: left;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
<p>You can put anything here</p>
<p>Yes, really anything!</p>
</div>
</div>
</div>
请参见这个Fiddle!