html - css selector not working without its class -
html:
<div id="header"> <div id="one"> <ul class="menu"> <li>one text</li> </ul> </div> <div id="two"> <ul class="menu"> <li>one text</li> </ul> </div> </div> this css won't work
#header ul.menu{ background-color: red; text-align: left; } #two ul{ /*this line*/ background-color: blue; text-align: right; } this css work
#header ul.menu{ background-color: red; text-align: left; } #two ul.menu{ /*this line*/ background-color: blue; text-align: right; } why so?
update
as per answers on css specificity #header ul.menu more specific #two ul. got ul.menu more specific ul.
ul.menu{...} #two ul{...} /* works exactly, yes #two more specific ul.menu */ okay, change order
order 1:
#header ul.menu{ background-color: red; text-align: left; } #two ul.menu{ /* selector works per specificity */ background-color: blue; text-align: right; } why #two ul.menu more specific #header ul.menu? (demo not required top first demo shows this)
order 2:
#two ul.menu{ background-color: blue; text-align: right; } #header ul.menu{ /* selector works per specificity */ background-color: red; text-align: left; } why #header ul.menu more specific #two ul.menu? demo
that's because class selector in #header ul.menu makes more specific #two ul, though #two "closer" ul in terms of structure. specificity doesn't care how "close" 1 element another. doesn't count combinators, if used #two > ul wouldn't make difference.
if you're going select same element, there no reason not balance selector specificity , either keep class selector in both rules:
#header ul.menu{ background-color: red; text-align: left; } #two ul.menu{ background-color: blue; text-align: right; } or remove both rules:
#header ul{ background-color: red; text-align: left; } #two ul{ background-color: blue; text-align: right; } depending on needs.
in update you've switched 2 equally specific rules around. later rule overrides earlier rule. again, regardless of element structure.
Comments
Post a Comment