我查看了如何将 block 居中放置在屏幕中间,我读到我必须将宽度指定为一个值,将边距指定为自动。
<head>
<style>
#CenteredBlock {
display: block;
position: absolute;
visibility: visible;
height: 70px;
width: 70%;
margin-left: auto;
margin-right: auto;
border-top-style: dotted;
border-right-style: dotted;
border-bottom-style: dotted;
border-left-style: dotted;
border-top-color: #000;
border-right-color: #000;
border-bottom-color: #000;
border-left-color: #000;
padding: 0%;
}
</style>
</head>
<body>
<div class="CenteredBlock" id="CenteredBlock"> Test </div>
</body>
我希望 block 占据屏幕的 70%,居中、左右各占 15%。如果我使用 margin-left: 15%;同样的,然后 block 居中,但我仍然想知道为什么当我指定宽度和边距时它不居中:auto
最佳答案
您不希望#CenteredBlock 绝对定位。你想让它“居中”。所以,删除“position:absolute”,一切都会正常工作。
关于css - 宽度和边距自动居中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20593868/