Search code examples
cssmenucss-selectorsparent-childcss-specificity

Can I use two child selector ".foo>a.bar>a", which is similar to ".foo.bar"?


I was making a menu list and would like to have a color change on the tab of current active page.

.menu>li>a {color: red;}
.menu>li>a.active>a {color: blue;}
<ul class="menu">
  <li class="active"><a href="">active page</a></li>
  <li><a href="">another page</a></li>
  <li><a href="">other page</a></li>
</ul>

(JS Bin)

In the code above, I want active page tab to be blue. However, I can't use .menu>li>a.active>a to change the color.

I remember that I can select classes like .foo.bar for a .foo under a specific condition .bar. However, like example above, it seems that I can't do it if there's child element, like .foo>a.bar>a.

Is this correct? Also, is there a better strategy for this kind of condition?


Solution

  • .menu>li>a {color: red;} .menu>li>a.active>a {color: blue;}

    Your above CSS code is wrong, that's why it's not working. You are having class="active" on <li> element, so you should use this css -

    .menu>li>a {color: red;}
    .menu>li.active>a {color: blue;}
    

    Also .foo.bar css selector will work on elements having both the class, for example -

    .foo.bar {
      color: dodgerblue;
    }
    <div class="foo bar">Multiple Class Element</div>