2

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>
Teamol
  • 733
  • 1
  • 14
  • 42

3 Answers3

2

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>
A Haworth
  • 30,908
  • 4
  • 11
  • 14
0

: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

Jeff
  • 48
  • 6
  • I use css grid and I need to style second column differently when there is only one row in the grid. – Teamol Oct 28 '21 at 16:17
  • So you can't do it in CSS. Because the end element is the element you're styling. There is no if statement in plain CSS. You can only do it in JS. – Izabela Furdzik Oct 28 '21 at 16:25
0

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>
Flagmans
  • 159
  • 1
  • 2
  • 16