I used a css selector to select the first child element.but it cant select the p tag’s first element.
here is the CSS code and the HTML code
article:first-child {
color: white;
}
article :first-child {
color: blue;
}
<body>
<h1>Jane Doe</h1>
<div class="job-title">Web Developer</div>
<p>Far far ge ocean.</p>
<p>1
<article>2</article>3</p>
<p>A small rio your mouth. </p>
<article>
<p>1</p>
</article>
<article>
<p>1</p>
</article>
<article>
<p>1</p>
</article>
</body>
The serial number “1” become blue but the number 2 between 1 and 3 didn’t has any change. It makes me confused.
2
Answers
When you read an article (like in a magazine), does that contain paragraphs? Yes, makes sense to split up a wall of text into small paragraphs.
But a paragraph can’t contain the article (logically). It’s a series of words, it means nothing without context. You could have multiple articles with just one paragraph, but a paragraph is a part of something, not the something itself.
The reason a
div
does work, is becausediv
stands for division (eg a part, an area, a section). And an area can have an article, eg ‘RightSide’.Semantics (ie what the element represents) is important in html. It helps browsers and crawlers and screenreaders etc to see what part of the site is what (eg a
<aside>
is not the main attraction, a<p>
contains a block it text intended to be read, etc).Maybe a helpful analogy: A tire is part of a car, a car is not part of a tire.
Not withstanding the semantic errors in your html as pointed out by others, the first-child selector cannot filter out other tags, quite literally the p tag has to be the first child of the parent . See here as to why. Try :first-of-type instead as per the code below. Hope this helps.