only-child selector using classes

Viewed 125

I would liky to select single div with specific class using only-child pseudo selector. I was hoping something like this would work.

.foo .bar:only-child {
  background-color: red;
}
<div class="foo">
  <div>1</div>
  <div class="bar">2</div>
  <div>3</div>
</div>

but this does not work, does it work with classes or only with types?

Solution:

Ok so I finally found the solution but since this is marked as duplicate (which I don't think it is) I will post it here

.foo bar:only-of-type {
  background-color: red;
}
<div class="foo">
  <div>1</div>
  <bar>2</bar>
  <div>3</div>
</div>

3 Answers

At the moment it seems that only Safari supports nth-child with an option of specifying a class (i.e. so it's not only the type, the tag name, which is matched).

This snippet selects your one and only div with class bar on Safari (tested on IOS) but not on Edge/Chrome (Windows10). See caniuse.com.

.foo div[class="bar"]:nth-child(1 of .bar):nth-last-child(1 of .bar) {
  background-color: red;
}
<div class="foo">
  <div>1</div>
  <div class="bar">2</div>
  <div>3</div>
</div>

:only-child matches the current selection that's also an only child (has no siblings). A valid match for .foo .bar:only-child would be the following:

<div>
    <div class="foo bar"></div>  
</div>

Your provided HTML has no only children. I'm not sure of your intentions but this may be the selector you're looking for: .foo > .bar

I don't think it is possible using only-child selector. But you can use > combinator which will select specific class .bar among children.

.foo > div.bar {
  color: red;
}
<div class="foo">
  <div>1</div>
  <div class="bar">2</div>
  <div>3</div>
</div>

Related