Below is a simple piece of HTML/CSS code, where I put in two URLs:
- The 1st URL (Google) is a child of the div.
- The 2nd URL (Bing) is only a descendant of the div.
Child-selector use implies that only the Google URL should be colored Red.
But in implementation, somehow both Google and Bing URLs are Red. (Also, interestingly, when I remove the <h1>Text</h1> element, then only the Google URL is colored Red.)
What is the reason?
Here is the HTML extract:
<div class="mydiv">
<a href="http://www.google.com">Google</a>
<p>
<h1>Text</h1>
<a href="http://www.bing.com">Bing</a>
</p>
</div>
And the CSS extract:
.mydiv > a {
color:red;
}
This is kind of tricky.
First of all
<h1>is a block-element. Next to note is, that<p>can only contain inline elements. As soon as a block element is encountered as a child of a<p>element, the opened<p>is implicitly closed.So (internally) your HTML snippet is transformed to this (for all I know the closing
</p>is ignored then):Now, as you can see, both
<a>tags are direct descendants of your<div>and so your CSS rule applies to both of them.The behavior, when removing the
<h1>tag follows accordingly: Your<p>is not implicitly closed. As such the second<a>remains a child of<p>and the CSS does not apply to it.I think, what you want to have is best achieved using another
<div>instead of the<p>tag (maybe even<article>,<section>or similar).