1

Day 26: using combinators in :has()

 1 year ago
source link: https://www.matuzo.at/blog/2022/100daysof-day26/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Day 26: using combinators in :has()

posted on October 31., 2022

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>
Letters

a b

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

31.10.2022

Teaser text

See on CodePen.

Further reading


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK