为什么我的 CSS 属性被覆盖/忽略? [英] Why are my CSS properties being overridden/ignored?

查看:99
本文介绍了为什么我的 CSS 属性被覆盖/忽略?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 CSS层次结构"方面遇到了一些问题(不确定将其称为层次结构是否合适).我正在尝试为下面的 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 都会发生变化,因此我想在所有页面上保持一致的样式,因此我编写了一些全局"CSS 规则.

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 样式,因此我编写了这些规则.

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:

由于某种原因,规则 #content p, #content li 覆盖了我的 .item-description.item-meta.我的印象是类/id 名称被认为是特定的,因此具有更高的优先级.但是,我似乎对 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?

另外,我在哪里可以阅读更多关于这种层次结构如何工作的信息?

Also, where can I read up more about how this hierarchy works?

推荐答案

元素 id 在 CSS 中具有优先级,因为它们是最具体的.你只需要使用 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 的优先级高于标签的优先级(p,li,ul,h1...).要覆盖规则,只需确保您拥有优先权;)

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 属性被覆盖/忽略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆