This content originally appeared on Manuel Matuzović - Web development blog and was authored by Manuel Matuzović
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
This content originally appeared on Manuel Matuzović - Web development blog and was authored by Manuel Matuzović
Manuel Matuzović | Sciencx (2022-10-31T09:38:54+00:00) Day 26: using combinators in :has(). Retrieved from https://www.scien.cx/2022/10/31/day-26-using-combinators-in-has/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.