Search code examples
cssstylesheet

CSS Specificity


Assuming this mark-up:

<html class="fr">
<head>
</head>
<body>
 <div class="class1">
 </div>
</body>
</html>

Will this:

.fr .class1 {
  background-color: blue;
}

take precedence over this:

.class1 {
  background-color: red;
};

Edit:

To those wondering, yes I had tried :) I didn't explain the full problem here and discovered the issue after this post.

Basically, I had two styles in the same stylesheet:

.fr .class1 {
  font-size: 12px;
}

.class1 {
  font-size: 12px;
  line-height: 18px;
  height: 80px;
}

While technically .fr .class1 takes precendence over .class1, this doesn't mean the element replaces all of .class1's styles with .fr .class1's styles. Instead, it looks at .fr .class1 for styles first, then .class1. This is "obvious" but this was why I was running into difficulty.

My goal was to remove styles by using .fr .class1's precedence over .class1. In order to do this, I realized I need to set values to 0 or neutral values:

Example)

.fr .class1 {
  font-size: 12px;
  line-height: 0;
  height: auto;
}

Otherwise, it will cascade to .class1 and fill these styles in.


Solution

  • Yes, since .fr .class1 references two class names and .class1 only references one, the first is more specific. The rules in the CSS standard are here.