Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

css selectors - Why are my CSS properties being overridden/ignored?

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>

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;
}

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;
}

However, I ran into some issues. Here is how Chrome is rendering the CSS:

Screenshot of how Chrome is rendering my 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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

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 ;)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...