Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Target the first element only if it has other siblings

Without adding any classes (or touching the HTML) is there a way to target the first element inside a div ONLY if there is a second element in that div? Below is my HTML:

<div class="grid">
    <div class="content">I WANT TO APPLY CSS TO THIS</div>
    <div class="content">But only if there is 2nd .content element in the same parent element</div>
</div>
<div class="grid">
    <div class="content">Don't apply here</div>
</div>
<div class="grid">
    <div class="content">Don't apply here</div>
</div>
<div class="grid">
    <div class="content">I WANT TO APPLY CSS TO THIS</div>
    <div class="content">But only if there is 2nd .content element in the same parent element</div>
</div>

A few context to this for a better picture ... I want to center the .content if it's the only .content inside .grid. But if there are two .content divs, then I want them to float next to each other.

Note:

I already know I can target the second .content by

.grid .content:nth-child(2) { ... }
like image 580
Ruby Avatar asked Jan 06 '16 01:01

Ruby


1 Answers

.grid > .content:first-child:not(:only-child) {
    color: blue;
}
<div class="grid">
    <div class="content">I WANT TO APPLY CSS TO THIS</div>
    <div class="content">But only if there is 2nd .content element in the same parent element</div>
</div>
<div class="grid">
    <div class="content">Don't apply here</div>
</div>
<div class="grid">
    <div class="content">Don't apply here</div>
</div>
<div class="grid">
    <div class="content">I WANT TO APPLY CSS TO THIS</div>
    <div class="content">But only if there is 2nd .content element in the same parent element</div>
</div>

:first-child:not(:only-child) would be your selector.

like image 158
MortenMoulder Avatar answered Nov 16 '22 16:11

MortenMoulder