CSS - Functional Selectors and functions

The :is Functional Selector

Pop-Quiz 1:

What do these select?

.a p {
background-color: red;
}
  • If you said: any element with the class a and a descendant p: then you would be correct. Spaces apply to descendants in css:

Pop-Quiz 2:

What if you wanted to apply a selector to the tags only within the div - what would you do?

<div class="a">
	<p> hello </p>
	<h1> world</h1>
</div>
<!--  nothing will or should happen here: -->
<p class="a"> a red background will not apply here  </p>
<h1 class="a"> a red background will not apply here</h1>
.a p {
background-color: red;
}
.a h1 {
background-color: red;
}

/*or you can use a functional selector*/

What about using a functional selector?

It works just as well as the above, but is more concise:

.a :is(p, h1){
	background-color: red;	
}

Playground

Try the above :is functional selector in this playground.

The :not Functional Selector

*Pop-Quiz: How would you make a red background apply and not apply here:

<div class="a">
	<p> a red background should not apply here </p>
	<h1> a red background should not apply here </h1>
  
  <h2> should apply </h2>
</div>

Answer:

.a :not(p, h1){
	background-color: red;	
}

The not selector conveniently allows the h2 to be coloured.

Try the above in the playground here.

The attr Selector

<a href="https://benkoshy.github.io/"> test </a>
a::after {  
  content: attr(href)
}

Checkout the playground

The calc function

You can incorporate custom properties with the var and calc functions:

<div class="a">
  big big big big big big big big big
</div>
<div class="b">
	should be half the width of the above
</div>
:root{
  --my-width: 6ch;
}

.a {
  width: var(--my-width);
}

.b {
  margin-block-start: 10ch;  
  width: calc(var(--my-width) - 50%);
}

Checkout the playground here.

Written on January 29, 2025