CSS Functions

CSS functions are a type of value that can represent more complex, calculated values.

calc() Value

The calc() function takes two arguments and calculates a result from the operator (+, -, *, /) you supply it, provided those arguments are numbers with or without an accompanying unit.

margin: 0 calc(50% - 50vw);

Breakout Section

attr() Value

The attr() value lets you take the value from an attribute, and reuse it in your CSS. In this example, I’m taking the href value from a link ad displaying it after the link text. I use this on my print.css stylesheet so that pages that are printed will show the link href values.

a[href*="//"]:not([href*="www.htmlhobbyist.com"])::after{
  content: " " attr(href) " ";
  text-decoration: underline;
}

Pseudo-Class Selectors

:not()

This pseudo-class selector will select anything that isn’t what you specify. The example code selects every section element that ins’t a first child.

section:not(:first-child) {
  margin-top: 0;
}

:is()

The :is() pseudo-class selector accepts a range of selectors as its argument. You can use it to simplify groups of selectors.

You could simplify this selector:

section h1, section h2, section h3, section h4, section h5, section h6, article h1, article h2, article h3, article h4, article h5, article h6, aside h1, aside h2, aside h3, aside h4, aside h5, aside h6 {
  color: white;
}

to this:

:is(section, article, aside) :is(h1, h2, h3, h4, h5, h6) {
  color: white;
}

The specificity of :is() will match the highest specificity in the provided selector list.

:where()

The :where() selector works much like the :is() selector, but the specificity of :where() will be 0.

:lang()

Used to select the language that the current selector is using. One common use for this selector is for things like internationalization.

:nth- Selectors

The :nth- pseudo-class selectors are similar to :first-child and :last-child selectors, but allow you to pass in a further value to change the selector behavior.

:nth-child()

The :nth-child selector allows you to pass in an argument to select one or more items. The following code will select the third list item:

.thirdItem li:nth-child(3)::marker {
  color: red;
}
  • One
  • Two
  • Three
  • Four
  • Five
  • Six

Select the top three items in a list:

.top3 li:nth-child(-n+3)::marker {
  color: red;
}
  • One
  • Two
  • Three
  • Four
  • Five
  • Six

Select all of the odd items in a list:

.odd li:nth-child(odd)::marker {
  color: red;
}
  1. One
  2. Two
  3. Three
  4. Four
  5. Five
  6. Six

:nth-of-type()

Matches siblings of the same type of element.

:nth-last-child()

Matches nth sibling from the last.

:nth-last-of-type()

Matches nth sibling from the last sibling of the same type of element.