Exploring Code #4: Has() Selector in CSS

Exploring Code #4: Has() Selector in CSS

There's a new selector in CSS that you should be aware of: the has() selector.

And currently, global usage is up to 87.5% as of today with only Firefox lagging behind.

I'd still suggest using it though - with a small fallback for Firefox.

Here are a few examples:

figure:has(figcaption) { … }

/* 
Matches <figure> elements that have a <figcaption>
*/

h1:has(+ p) { … }

/*
Matches <h1> elements only if they have a <p> element directly following.
*/
        

Pretty cool.

One really useful example I found in this article was styling forms based on HTML attributes:

<form action="" method="get">
 <p> 
  <label for="name">Name</label>
  <input type="text" id="name" required>
  </p>
  <p>
  <label for="dob">Date of Birth: </label>   <input id="dob" name="dob" type="date" placeholder="YYYY-MM-DD" min="1900-01-01" required /> 
  </p>
</form>

<style>
p:has(:required) label::after {
  content: "(required)";
}
*:has( > label + :required:invalid) > label {
  font-style: italic;
}
p:has(:required:invalid) label {
  color: red;
}
</style>        

Output of this code (not pretty, but you get the idea)

Basically, what we are doing is styling any input with the required tag that's inside of a p tag.

And on the second line we are using the universal * selector as a replacement for the p tag (in this case grabbing the same thing but in a flexible way if we added more markup).

But as you can see, the selector gets pretty powerful as you drill down into it:

has() is not just a parent selector.

div.whaddup:has(img
[src="https://images.bauerhosting.com/legacy/media/6262/e2bf/209b/55c1/b411/232b/7-con-air.jpg?]) 

{
    border: 10px red dotted;
    color: hsla(194, 100%, 50%, 1); /* some blue color */
  }        

When you want to get more specific with your selections, it's actually a child selector as well:

div with a class of 'whaddup' that has an image with the Nick Cage source ==> and then we style that specific image.

div.whaddup:has(img[src="https://images.bauerhosting.com/legacy/media/6262/e2bf/209b/55c1/b411/232b/7-con-air.jpg"]) > img {
  height: 100px;
  max-width: 100%;
  color: hsla(194, 100%, 50%, 1); /* some blue color */
}        


I'm still trying to wrap my head around it and get comfortable with looking at CSS selectors this way, so I might still get things wrong with it.

But practice makes perfect.

Sam O'Barr

Lead Developer / Developer Manager at National Academy of Sports Medicine (NASM)

1 年

Look at this guy, writing blogs post about coding now!

回复
Dustin Porchia

Founder, Beard Organics LLC & Senior Front End Developer at National Academy of Sports Medicine

1 年

You should write about not() next!

回复

要查看或添加评论,请登录

Gabriel Thurau的更多文章

社区洞察

其他会员也浏览了