css - 宽度和边距自动居中不起作用

标签 css width block center margins

我查看了如何将 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/

相关文章:

html - 如何自定义登陆页面 ("Blocked by Netgear"- 更改为 "Blocked by house owner"等)

html - 大屏和小屏Html分开href url

php - HTML/PHP 网站的 ASP.NET 母版页等效项

javascript - 鼠标从触发器移开后保持 Div 可见(jQuery)

html - Bootstrap 4 beta - cols 计算不正确

Java 按钮宽度

css - 最佳就地额外宽度会破坏布局

html - 需要固定站点宽度以删除水平滚动条

Magento 从 Mage 命名空间调用我的命名空间 block

css - 自定义初始页面上的奇怪 float /宽度问题(动态调整大小)(