如何垂直和水平居中高度未知的 div
How to vertically and horizontally center a div of unknown height
我尝试使用 flexbox 方法、table 方法和其他一些方法将未知高度的 div 垂直居中,但我的 div 没有正确居中。我希望居中 div 的宽度为 window 宽度的 50% 或者最小宽度为 200px。
.content {
background-color: violet;
min-width: 200px;
width: 50%;
margin-left: auto;
margin-right: auto;
box-shadow: 0px 1px 7px 1px rgba(0, 0, 0, 1);
}
.outer-container {
display: table;
width: 100%;
background-color: violet;
}
.container {
display: table-cell;
text-align: center;
vertical-align: middle;
}
<body>
<div class="outer-container">
<div class="container">
<div class="content">
<div class="title-class">
Hello there
</div>
</div>
</div>
</div>
</body>
使用 flexbox,这里是您需要的所有代码:
HTML
<div class="container">
<div class="content">
<div class="title-class">Hello there</div>
</div>
</div>
CSS
html, body { height: 100%; }
.container {
display: flex;
justify-content: center;
align-items: center;
background-color: violet;
height: 100%;
}
.content {
background-color: violet;
width: 50%;
text-align: center;
box-shadow: 0px 1px 7px 1px rgba(0, 0, 0, 1);
}
作为替代方案,这里是 table 方法:
- How to Center Elements Vertically, Horizontally or Both
我尝试使用 flexbox 方法、table 方法和其他一些方法将未知高度的 div 垂直居中,但我的 div 没有正确居中。我希望居中 div 的宽度为 window 宽度的 50% 或者最小宽度为 200px。
.content {
background-color: violet;
min-width: 200px;
width: 50%;
margin-left: auto;
margin-right: auto;
box-shadow: 0px 1px 7px 1px rgba(0, 0, 0, 1);
}
.outer-container {
display: table;
width: 100%;
background-color: violet;
}
.container {
display: table-cell;
text-align: center;
vertical-align: middle;
}
<body>
<div class="outer-container">
<div class="container">
<div class="content">
<div class="title-class">
Hello there
</div>
</div>
</div>
</div>
</body>
使用 flexbox,这里是您需要的所有代码:
HTML
<div class="container">
<div class="content">
<div class="title-class">Hello there</div>
</div>
</div>
CSS
html, body { height: 100%; }
.container {
display: flex;
justify-content: center;
align-items: center;
background-color: violet;
height: 100%;
}
.content {
background-color: violet;
width: 50%;
text-align: center;
box-shadow: 0px 1px 7px 1px rgba(0, 0, 0, 1);
}
作为替代方案,这里是 table 方法:
- How to Center Elements Vertically, Horizontally or Both