Day 26: using combinators in :has()
posted on
It’s time to get me up to speed with modern CSS. There’s so much new in CSS that I know too little about. To change that I’ve started #100DaysOfMoreOrLessModernCSS. Why more or less modern CSS? Because some topics will be about cutting-edge features, while other stuff has been around for quite a while already, but I just have little to no experience with it.
You already know that the :has()
pseudo-class allows you to check whether a parent element contains certain children, but you can also make this selector more specific, or check other relations the element might have.
Child combinators
You can check whether an element contains a specific direct child element.
For example, if you have a fieldset
and you want to make sure that it contains a legend
and that this legend
is actually a direct child item of the fieldset
, which is important, you could use the child combinator (>
) in your :has()
pseudo-class.
fieldset:not(:has(> legend)) {
border: 10px solid red;
}
<fieldset>
<div>
<legend>Letters</legend>
</div>
<input type="radio" name="letters" id="a">
<label for="a">a</label>
<input type="radio" name="letters" id="b">
<label for="b">b</label>
</div>
</fieldset>
Next-sibling combinators
:has()
is not just a parent selector, you can select elements based on other relations, too. By using the next-sibling combinator, you can check whether an element has a specific next sibling element, and style it accordingly.
h2 {
margin-block-end: 0.7em;
}
h2:has(+ time) {
margin-block-end: 0;
}
The <h2>
has a block end margin of 0.7em
by default, but when its next sibling is a <time>
element, the margin is 0.
Heading
Teaser text
Heading
Teaser text
Further reading
- Day 6: the :has() pseudo-class
- Day 8: nesting :has()
- Day 16: the specificity of :has()
- Day 50: :has(:not()) vs. :not(:has())
- Day 91: a previous sibling selector with :has()
- :has(): the family selector
Overview: 100 Days Of More Or Less Modern CSS