two css rules “seemingly” have same specificity weight but doesn't produce the same result
-
28-06-2021 - |
Question
Ok, I'm trying to understand the CSS cascade and specificity as a "science" and not always leaving it up to "hit or miss" approach. I hope someone will help me out.
I have a rule:
.bluebutton {margin: 0 10px 6px 0;} /* rule 1 */
That I need to overwrite to change the margins in a particular instance.
So I added a class
to the div
and wrote:
.aside-right .bluebutton a {margin:30px 0 0 100px;} /* rule 2 */
However, rule 2 did not overwrite rule 1.
So I modified rule 2 to this:
.aside-right a.bluebutton {margin:30px 0 0 100px;} /* rule 3 */
and it overwrites the ".bluebutton
" rule. /* rule 1 */
At first I wrote this HTML
<a class="blueButton aside-right" href="enrollNow.html"><span>Enroll Now</span></a> <!-- html-1 -->
Then I modified and contained the button within a div
and wrote:
<div class="aside-right"><a class="blueButton" href="enrollNow.html"><span>Enroll Now</span></a></div> <!-- html-2 -->
html-2 worked with rule 3.
Can someone help me understand why rule 3 overwrites rule 1 yet, rule 2 does not overwrite rule 1? It looks like rules 2 and 3 have the same weight (to me). Is it because rule 2 targets any anchor
tag within any element with a class
of .bluebutton
and .aside
, yet rule 3 targets only anchor
tags with a class
of .bluebutton
? I hope I explained what I'm trying to understand clearly.
Thanks!
Solution
Rule 1
.bluebutton
will target any element with the class bluebutton
.
Rule 2
.aside-right .bluebutton a
will target an anchor element nested inside an element with class="bluebutton"
, nested inside an element with class="aside-right"
. Example structure:
<div class="aside-right">
<div class="bluebutton">
<a href="#">link</a>
<div>
<div>
Rule 3
.aside-right a.bluebutton
will target any anchor with class="bluebutton"
nested within an element with class="aside-right"
. Example structure:
<div class="aside-right">
<a class="bluebutton" href="#">link</a>
<div>
OTHER TIPS
Rule 2 does not select the same elements as rule one.
Rule 1 selects any element with bluebutton
class
Rule 2 selects <a>
elements that are descendants of element with bluebutton
class which are descendants of element with aside-right
class, from the html elements with the bluebutton
class has no <a>
descendants
.bluebutton a
and a.bluebutton
are not equivalent. The first finds a
elements that are inside an element with the class bluebutton
. The second finds elements that are a
elements with the class bluebutton
.