【问题标题】:Width and margin auto to center not working宽度和边距自动居中不起作用
【发布时间】:2014-01-02 20:05:35
【问题描述】:

我查看了如何在屏幕中间将块居中,我读到我必须将宽度指定为一个值,并将边距指定为自动。

<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

【问题讨论】:

    标签: css width block center margins


    【解决方案1】:

    您不希望#CenteredBlock 绝对定位。您希望它“居中”。因此,删除“位置:绝对”,一切都会正常工作。

    【讨论】:

    • (因为我现在不能回答我的问题,所以我会发表评论)好的,现在的问题是让块从顶部的“最零”像素开始。现在它在块和浏览器栏之间留下了一个空白! :P
    • 这个新问题并非源自#CenteredBlock div。由于浏览器默认样式,出现了这种差距。所有的浏览器都会添加一些 CSS 来合成,这就是我们使用重置样式表的原因。因此,要解决这个新问题,您可以使用 reset.css(互联网上有很多选项)或直接重置与您的布局冲突的那些。我敢打赌,添加:body { margin: 0;填充:0; } 将使差距消失。
    • 是的,在我问的另一个问题中,有人也回答了这个问题。我想我本来可以等你回答的^_^“还是谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-05-01
    • 2013-05-24
    • 2021-08-13
    • 2017-01-10
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    相关资源
    最近更新 更多