【问题标题】:Align a DIV tag without knowing the width [duplicate]在不知道宽度的情况下对齐 DIV 标签 [重复]
【发布时间】:2012-01-01 00:48:55
【问题描述】:

可能重复:
How can I center something if I don't know ahead of time what the width is?

我想知道如何在不知道宽度的情况下对齐 div 标签。这与其他问题不同,因为我不介意使用 <center> 标记,但它在 HTML 组视图中似乎是“旧的”。 <center> 标记将来是否仍然有效?

谢谢

【问题讨论】:

标签: html css center


【解决方案1】:

我通常使用width:autowidth:100% 而不是margin:0 auto

但是,您可以在下面的链接中看到与您的问题几乎相同的详细信息!

How can I center align a div without knowing the width?

【讨论】:

    【解决方案2】:

    通过将左右边距设置为自动来使块元素居中。

    margin-left: auto;
    margin-right: auto;
    

    <center> 工作在可预见的将来会继续工作,所以没有技术上的理由不使用它,但是在现代 Web 开发中,应该承认“separation of presentation and content”的原则,并使用 HTML 作为语义和 CSS布局。

    【讨论】:

    • 也可以使用简写margin: 0 auto;
    • 检查一下为什么不使用中心stackoverflow.com/questions/1798817/…
    • @sandeep:我不明白你想说什么。 <center> 的全部问题在于它混淆了块和文本居中。这就是为什么它被“拆分”成margin: auto(用于块)和text-align: center(用于文本),并且使用text-align 来使块居中是错误的。
    【解决方案3】:

    这样写:

    #parent {
        text-align:center;
    }
    .child {
        display:inline-block;
        *display:inline /* IE */
        *zoom:1;/* IE */
        text-align:left;
    }
    

    检查一下

    http://jsfiddle.net/efEgq/2/

    【讨论】:

    • text-align 用于对齐文本(因此得名)。
    • 嘿@RoToRa;谁说 text-align 仅用于对齐文本。它也对齐内联标签,例如 等。
    • 没有错误的标记,也没有任何错误的 css。
    • +1 显示:inline-block;
    • W3C 确实如此。使块居中和使正在运行的文本居中是两个完全不同的概念。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    相关资源
    最近更新 更多