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!
Rule 1
.bluebuttonwill target any element with the classbluebutton.Rule 2
.aside-right .bluebutton awill target an anchor element nested inside an element withclass="bluebutton", nested inside an element withclass="aside-right". Example structure:Rule 3
.aside-right a.bluebuttonwill target any anchor withclass="bluebutton"nested within an element withclass="aside-right". Example structure: