如何垂直和水平居中未知高度的div [英] How to vertically and horizontally center a div of unknown height
本文介绍了如何垂直和水平居中未知高度的div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试过使用flexbox方法,table方法和其他一些垂直居中未知高度div的方法,但我的div没有正确居中。我希望居中div的宽度为窗口宽度的50%,或者最小宽度为200px。
.content {background彩色:紫罗兰色; min-width:200px;宽度:50%; margin-left:auto; margin-right:auto; box-shadow:0px 1px 7px 1px rgba(0,0,0,1);}。outer-container {display:table;宽度: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>你好< / div> < / DIV> < / DIV> < / div>< / body>
解决方案 使用flexbox,以下是您需要的所有代码:
HTML b $ b
< 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;
身高:100%;
}
.content {
background-color:violet;
宽度:50%;
text-align:center;
box-shadow:0px 1px 7px 1px rgba(0,0,0,1);
}
另外,下面是表格方法: / p>
I tried using the flexbox method, table method, and some other methods for vertically centering a div of unknown height, but my div is not getting centered correctly. I want the width of the centered div to be 50% of the window width or have a min-width of 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>
解决方案
Using a flexbox, here's all the code you need:
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);
}
As an alternative, here's the table method:
这篇关于如何垂直和水平居中未知高度的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文