首页 > 解决方案 > 为什么定义给类的样式不能在

元素?

问题描述

我对 CSS 和 HTML 很陌生,遇到了我有一个 classexample和一个 class的情况credits。我希望里面example的一些元素有一个特定的设计,但是credits是通用的,应该适用于整个文档。所以我写道:

.example p {
    text-align: justify;
}
.credits {
    text-align: right;
}
<div class="example">
    <h1>Main Title</h1>
    <p class="credits">by Author</p>
  <p class="intro">some info...</p>
  <h2>Title</h2>
  <p>Lots of text...</p>
</div>

我的问题是:.credits样式不适用于<p class="credits">内部元素<div>,我不明白为什么。有人可以解释一下原因吗?

标签: htmlcss

解决方案


您遇到了 CSS 选择器特异性的问题。

当 CSS 从样式表的顶部到底部评估规则时,它还查看选择器的特殊性以确定首先应用哪个规则,第二个,第三个,等等。

选择.example p器比选择器具有更高的特异性(两个选择器),.credits因此它被第二个应用并覆盖后面的选择器。

如果您更新第二个选择器以具有更多特异性,(例如.example .credits)它将为您提供您正在寻找的输出。

.example p {
    text-align: justify;
}
.example .credits {
    text-align: right;
}
<div class="example">
    <h1>Main Title</h1>
    <p class="credits">by Author</p>
  <p class="intro">some info...</p>
  <h2>Title</h2>
  <p>Lots of text...</p>
</div>


推荐阅读