How can I make this link use the child selector without changing or removing the parent selector? (I want the link to be blue.)
<html>
<head>
<style>
.parent a { color:Red; }
.child { color:Blue; }
</style>
</head>
<body>
<div class="parent">
<a class="child" href="http://www.stackoverflow.com">
stackoverflow
</a>
</div>
</body>
</html>
It is surprising to me that the parent overrides the child in this case!
Descendant selectors are used to apply styles specifically to elements nested within other elements. To select a descendant element, use a space between the selectors to denote the nested relationship. The selector on the left is the ancestor element. The selector on the right is the descendant element.
The descendant selector is a way to select elements that are located somewhere underneath other elements, according to the tree structure of the webpage. This selector is actually multiple selectors combined together, but separated by a space.
One important note is that a child selector is going to be faster than descendant selector, which can have a visible affect on pages with 1000's of DOM elements. Good answer, but I'd simply add on direct answers to his examples in the question as well -- just to make it ridiculously clear.
Use a.child
as the selector.
<html>
<head>
<style>
.parent a { color:Red; }
a.child { color:Blue; }
</style>
</head>
<body>
<div class="parent">
<a class="child" href="http://www.stackoverflow.com">
stackoverflow
</a>
</div>
</body>
</html>
This is due to CSS specificity. The extra a
after .parent
makes it more specific than just .parent
, and correspondingly, more specific than just .child
. Obalix's suggestion gives the selectors the same specificity, with both having a base HTML element and a class designation. When specificity is equal, it will then apply the deepest value specified in the hierarchy, as you were expecting.
This article (and the resources to which it links) do a great job explaining CSS specificity: http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html
For future exploring http://css-tricks.com/specifics-on-css-specificity/
basically you can count selectors value in this order
Inline | ID | Class/pseudoclass | Element
1 | 1 | 1 | 1
where Inline = 1000, ID = 100, Class = 10, Element = 1
In your case
.parent a == 11
and .child == 10
thats why parent overrides child element style.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With