【问题标题】:CSS: text-indent and text-align are ignoredCSS:文本缩进和文本对齐被忽略
【发布时间】:2014-08-31 00:37:29
【问题描述】:

我想这个问题的答案可能很简单,但我自己无法弄清楚。

我有以下 HTML:

<div id="excerpt">
    <p class="chapter">Chapter One</p>
    <p>Text</p>
    <div class="copyright-notice">
        <p>Copyright &copy; 2014 Name. All rights reserved.</p>
    </div>
    <!--end copyright-notice-->
</div>
<!--end excerpt-->

和下面的 CSS 一起去:

#excerpt {
    padding:20px;
    color:#000000;
}
#excerpt p {
    line-height:1.4em;
    text-indent:45px;
    text-align:justify;
}
p.chapter {
    text-align:center;
    text-indent:0;
    font-size:16pt;
    text-transform:uppercase;
}
.copyright-notice {
    border-bottom: 1px solid #999999;
    border-top: 1px solid #999999;
    margin:20px auto;
    padding:20px;
}
.copyright-notice p {
    display: block;
    color:#666666;
    text-align: center;
    text-indent:0;
}

JS Fiddle reproduction.

如您所见,我尝试将文本居中并将带有章节类的段落以及版权声明中的文本的缩进设置为 0。但它不起作用。 如果我将样式直接应用于 HTML 文件中的段落,例如:

<p style="text-align:center;text-indent:0;">text</p>

JS Fiddle reproduction.

它会起作用的。但是,一旦我尝试通过 CSS text-align 和 text-indent 设置这些段落的样式,就会被忽略。

知道我做错了什么吗?感谢您的帮助!

【问题讨论】:

    标签: html css text-align text-indent


    【解决方案1】:

    这只是一个specificity 问题。

    选择器#excerpt pp.chapter 更具体。因此text-indent:0 不适用。使用 style 属性时应用它的原因是因为内联 CSS 更具体。

    更具体地说,(双关语),#excerpt p 的特异性计算为 101。而p.chapter 的特异性为 11。(id 为 100 分,类为 10,元素为 1)。

    至于解决方案,请使用以下任一方法以避免特异性冲突。

    p {
        text-indent:45px;
    }
    p.chapter {
        text-indent:0;
    }
    

    或者..

    #excerpt p {
        text-indent:45px;
    }
    #excerpt p.chapter {
        text-indent:0;
    }
    

    (为简洁省略了其他样式。)

    后一个示例可能是您应该使用的,因为您不希望所有段落元素都缩进,只是那些#excerpt 的后代元素。我会尽量避免在 CSS 中使用 id's - 为 JS 保存那些。

    【讨论】:

    • 有一个确凿的JS Fiddle。为什么是的,你比我快一点。天哪... ;)
    • 非常有意义。非常感谢。
    猜你喜欢
    • 2019-02-04
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 2014-01-28
    相关资源
    最近更新 更多