开发者

CSS Specificity

开发者 https://www.devze.com 2023-03-31 01:17 出处:网络
Assuming this mark-up: <html class=\"fr\"> <head> </head> <body> <div class=\"class1\">

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, thi开发者_如何转开发s 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.


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.


Yes because the first example has two class names compared to one.

Example: http://jsfiddle.net/jasongennaro/yQvAF/

Try using this CSS specificity calculator: http://www.suzyit.com/tools/specificity.php


In response to the edit:

CSS applies the values to each property individually. Block grouping does not matter. So

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

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

is the same as

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

which, as .fr .class1 is more specific than .class1 alone, is the same as

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

精彩评论

暂无评论...
验证码 换一张
取 消