我一直在使用display: table我html连同display: table-cell我的body表演,使我的所有网页的内容出现在屏幕的正中心.虽然,这适用于段落,标题,输入和标签等(至少我已经测试过),它似乎不适用于div元素.
有没有办法让div元素像其他元素一样工作?纯CSS解决方案是最好的.
示例(也在Codepen上)
html {
display: table;
height: 100%;
width: 100%;
text-align: center;
}
body {
display: table-cell;
vertical-align: middle;
}
.hidden {
display: none;
}
.leaf {
border-radius: 15px 2px 15px 2px;
border: 1px solid green;
background-color: green;
width: 250px;
height: 80px;
}Run Code Online (Sandbox Code Playgroud)
<div class="leaf">Why am I not centered?</div>
<p>And why am I centered?</p>Run Code Online (Sandbox Code Playgroud)
只需添加margin: 0 auto;..正常工作.
html {
display: table;
height: 100%;
width: 100%;
text-align: center;
}
body {
display: table-cell;
vertical-align: middle;
}
.hidden {
display: none;
}
.leaf {
border-radius: 15px 2px 15px 2px;
border: 1px solid green;
background-color: green;
width: 250px;
height: 80px;
margin:0 auto;
}Run Code Online (Sandbox Code Playgroud)
<div class="leaf">Why am I not centered?</div>
<p>And why am I centered?</p>Run Code Online (Sandbox Code Playgroud)