問題描述
我在 CSS層次結(jié)構(gòu)"方面遇到了一些問題(不確定將其稱為層次結(jié)構(gòu)是否合適).我正在嘗試為下面的 HTML 設置樣式.
I'm having some issues with the CSS "hierarchy" (not sure if it's proper to call it a hierarchy). I'm trying to style the below bit of HTML.
<body>
<section id="content">
<article>
<ul class="posts-list">
<li class="post-item">
<h2>[post title]</h2>
<p class="item-description">...</p>
<p class="item-meta">...</p>
</li>
...
</ul>
</article>
</section>
</body>
由于我擁有的每個頁面上的 section#content 都會發(fā)生變化,因此我想在所有頁面上保持一致的樣式,因此我編寫了一些全局"CSS 規(guī)則.
Since section#content changes on every page I have, I wanted to maintain consistent styles across all of them, so I wrote some "global" CSS rules.
#content {
color: #000;
margin-left: 300px;
max-width: 620px;
padding: 0px 10px;
position: relative;
}
#content p,
#content li {
color: #111;
font: 16px / 24px serif;
}
我想在 ul.posts-list
中以不同的方式設置 HTML 樣式,因此我編寫了這些規(guī)則.
I wanted to style HTML within a ul.posts-list
differently, so I wrote these rules.
li.post-item > * {
margin: 0px;
}
.item-description {
color: #FFF;
}
.item-meta {
color: #666;
}
但是,我遇到了一些問題.下面是 Chrome 渲染 CSS 的方式:
However, I ran into some issues. Here is how Chrome is rendering the CSS:
由于某種原因,規(guī)則 #content p, #content li
覆蓋了我的 .item-description
和 .item-meta
.我的印象是類/id 名稱被認為是特定的,因此具有更高的優(yōu)先級.但是,我似乎對 CSS 的工作原理有誤解.我在這里做錯了什么?
For some reason, the rules #content p, #content li
are overriding my rules for .item-description
and .item-meta
. My impression was that class/id names are considered specific and thus higher priority. However, it seems that I have a misunderstanding of how CSS works. What am I doing wrong here?
另外,我在哪里可以閱讀更多關于這種層次結(jié)構(gòu)如何工作的信息?
Also, where can I read up more about how this hierarchy works?
推薦答案
元素 id 在 CSS 中具有優(yōu)先級,因為它們是最具體的.你只需要使用 id:
Elements id have the priority in CSS since they are the most specific. You just have to use the id:
#content li.post-item > * {
margin: 0px;
}
#content .item-description {
color: #FFF;
}
#content .item-meta {
color: #666;
}
基本上 id 的優(yōu)先級高于標簽的優(yōu)先級(p,li,ul,h1...).要覆蓋規(guī)則,只需確保您擁有優(yōu)先權(quán);)
Basically id have the priority on class which the priority on tags(p,li,ul, h1...). To override the rule, just make sure you have the priority ;)
這篇關于為什么我的 CSS 屬性被覆蓋/忽略?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!