1

I am trying to create css dropdown menu. I am trying with following html and css

 .nav > li{
    display: inline-block;   
}
.nav{
    background-color: #666666;
}
.nav a{
    color:#ffffff;
    text-decoration: none;
}
.nav .subnav .subs{
    display: none;
}

.subs{
    position: absolute;
    background-color: #444;
}
.subs a{
  display:block;
  padding:10px;
}

li:hover > ul  {
    display: block;
}
<ul class="nav">
    <li><a href="#">Home</a></li>
    <li class="subnav">
        <a href="#">Courses</a>
        <ul class="subs">
            <li><a href="#">B.tech</a></li>
            <li><a href="#">BSC</a></li>
        </ul>
    </li>
</ul>

Above code doesn't work because of I am selecting .subs like .nav .subnav .subs

.nav .subnav .subs{
    display: none;
}

But if I just do

.subs{
    display:none;
}

It works fine. My question is why its not working if I select element like .nav .subnav .subs ? and what difference.

Richerd fuld
  • 364
  • 1
  • 10
  • 23
  • It is because of CSS selector's priority / specificity. Read this question for more information. http://stackoverflow.com/questions/4072365/css-understanding-the-selectors-priority-specificity – Suresh Ponnukalai Jun 08 '15 at 06:11

1 Answers1

1

That's because of the selectors specificity. You need to be more specific in selectors when using different rules for same elements. Instead of

li:hover > ul {
    display: block;
}

Try:

li.subnav:hover > ul.subs {
    display: block;
}

i.e. more specific selector which targets the element.

If this doesn't work then you may use !important. I will not suggest you to go for this option. Better make the CSS selectors more specific.

K K
  • 17,794
  • 4
  • 30
  • 39