我抬起头看如何在屏幕中间居中放置一个块,并读到必须指定宽度值和自动设置边距。
<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>
我希望该块占据屏幕的70%,居中,左右分别设置为15%。如果我使用margin-left:15%;同样正确,然后块居中,但是我仍然想知道为什么当我指定宽度和边距时它不居中:auto
最佳答案
您不希望绝对定位#CenteredBlock。您希望它“居中”。因此,删除“ position:absolute”,一切都会正常。