Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS CSS Selectors Going Further with Attribute Selectors and Pseudo-Classes :only-child and :empty

Need help! Can you explain me bette how :only-child works??

Hi everybody, it's not clear to me how :only-child works. If i use only the command :only-child, how does the browser apply these styles and where?? I'm not specifying any selectors, so I don't understand where and why the browser applies the styles! Sorry, I'm a bit confused! Thanks!

2 Answers

Simon Owerien
Simon Owerien
12,829 Points

In this case the browser applies the styles to every element that is the only child of an element. For example:

<body>
<h1>Bla</h1>
<span><p>Yay</p></span>
</body>
:only-child{
color: green;
}

The green color doenst apply to "Bla" because <h1> is not the only child of <body> (<span> is another child of <body>). But it does apply to "Yay" because <p> is the only child of <span>

ywang04
ywang04
6,762 Points

Good example. Thanks a lot.

Sarah Dillon
Sarah Dillon
10,704 Points

It's a pseudo class so it doesn't necessarily need a tag to work.

:only-child selects any tag that is the only-child of a parent element

but you can select a tag if you wish i.e p:only-child which will only select <p> elements that are the only child of its parent element.

hope this helps :D