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;
  <input type="radio" name="letters" id="a">
  <label for="a">a</label>

  <input type="radio" name="letters" id="b">
  <label for="b">b</label>

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.


Teaser text


Teaser text

See on CodePen

Further reading

Do you want to learn even more awesome CSS?

I'm running a workshop with my friends at Smashing Magazine in which I introduce you to the most useful modern features in CSS and show how you can implement them today in your code base to improve scalability, maintainability, and productivity.

Learn more about the workshop!

Overview: 100 Days Of More Or Less Modern CSS