html - 为什么定义给类的样式不能在元素?
问题描述
我对 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>
,我不明白为什么。有人可以解释一下原因吗?
解决方案
您遇到了 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>
推荐阅读
- reactjs - React hooks useCallback 依赖于函数
- python - 使用 imgaug 增加数据集大小
- java - 我不知道为什么会出现这些输出,(java线程)
- javascript - 如何将 json 转换为 javascript 中的数组以获取 li 列表
- react-redux - React Redux Material-UI 自动完成
- c# - 使用 SWIG 从 C++ 回调到 C#
- sql - 什么是“NoSQL”数据库模型?
- go - 如何创建带有`New`前缀混淆的结构
- r - 在 ggplot 中使用两个程序定义变量的线性运算作为美学
- java - 如何在 Hibernate/JPA 中的两个表之间创建中间表?