How to horizontally center a <div> in another <div>?我设法从接受的答案中使用样式水平居中。我怎样才能将它垂直居中?内部div的高度未知。
答案 0 :(得分:7)
来自: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>
答案 1 :(得分:0)
这是一种很酷的技术,可以垂直和水平对齐盒子:
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>
另见this Fiddle!