kibibyte kibibyte - 2 months ago 6
CSS Question

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?

Answer

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