undefinedfix
Sign in

How does the CSS selector select the first child element?

AntimoV edited in Fri, 06 Jan 2023
<div class="test">
    <p>1</p>
    <span>2</span>
</div>
<div class="test">
    <span>1</span>
    <p>2</p>
</div>

Normally, the first child element should be. Test > P: first child or. Test > P span:first-child But if the HTML structure is not unified, such as the one I gave, I want to set the style for the first child element, how to write it? Suppose that the text color displayed by 1 is set to red color: red;

4 Replies
pazhitnov
commented on Fri, 06 Jan 2023

*Can't first child?

user2108228
commented on Fri, 06 Jan 2023

CSS can use wildcard *

So a demo of stylus is as follows

.test
  *:first-child
    color:red
// 亦或省略*号
.test
  :first-child
    color:red
cashsavings
commented on Fri, 06 Jan 2023

Just take the label test>:first-child

aongaiaha
commented on Fri, 06 Jan 2023

Should it be like this?

Select the first element under your test test:first-child :first-child{ color:red; }