Issue
I'm working with markup generated by a third-party app so I'm branding it and running into a scenario I can't solve. Most of the time the HTML will have two <div>
s in a container <div>
that have the same class name of formCol
. There's always a clear
sibling, too:
<div class="formRow">
<div class="formCol">Two Divs</div>
<div class="formCol">With the Same Class</div>
<div class="clear"></div>
</div>
Occasionally there's only one .formCol
in the container. I'd like to be able target when the formRow
has just one formCol
, but because clear
is still a sibling I can't use :only-of-type
or :only-child
.
<div class="formRow">
<div class="formCol">One Div</div>
<div class="clear"></div>
</div>
How can I target when formRow
has only one formCol
in it?
Solution
Assuming that .clear
is always there you can combine two nth-
pseudo classes:
/* it is the first child and the second last child at the same time */
:nth-child(1):nth-last-child(2) {
background-color: red;
}
<div class="formRow">
<div class="formCol">Two Divs</div>
<div class="formCol">With the Same Class</div>
<div class="clear"></div>
</div>
<hr>
<div class="formRow">
<div class="formCol">One Div</div>
<div class="clear"></div>
</div>
And if you only target latest version of browsers you can use new syntax of :nth-child
:
/* it is the first .formCol and the last .formCol at the same time */
:nth-child(1 of .formCol):nth-last-child(1 of .formCol) {
background-color: red;
}
<div class="formRow">
<div class="formCol">Two Divs</div>
<div class="formCol">With the Same Class</div>
<div class="clear"></div>
</div>
<hr>
<div class="formRow">
<div class="formCol">One Div</div>
<div class="clear"></div>
</div>
or :has
:
/* it is the first .formCol and next sibling is .clear */
.formCol:first-child:has(+ .clear) {
background-color: red;
}
<div class="formRow">
<div class="formCol">Two Divs</div>
<div class="formCol">With the Same Class</div>
<div class="clear"></div>
</div>
<hr>
<div class="formRow">
<div class="formCol">One Div</div>
<div class="clear"></div>
</div>
Answered By - Salman A
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.