Exploring CSS Functions in Detail | Custom Properties and CSS Functions

CSS functions provide built-in functionality for various tasks, allowing you to create dynamic and flexible styles. Here are some common CSS functions and their uses:

1. calc()

  • Purpose: Performs calculations on values.
  • Syntax: calc(expression)
  • Example:

CSS

.element {

  width: calc(100% – 20px);

  padding: calc(1rem / 2);

}

2. hsl() and hsla()

  • Purpose: Creates colors using hue, saturation, and lightness.
  • Syntax: hsl(hue, saturation%, lightness%) and hsla(hue, saturation%, lightness%, alpha%)

Example:

CSS

.element {

  background-color: hsla(200, 50%, 70%, 0.8);

}

3. rgb() and rgba()

  • Purpose: Creates colors using red, green, and blue values.
  • Syntax: rgb(red, green, blue) and rgba(red, green, blue, alpha)

Example:

CSS

.element {

  color: rgba(255, 0, 0, 0.5);

}

4. var()

  • Purpose: References custom properties.
  • Syntax: var(–custom-property-name)

Example:

CSS

:root {

  –primary-color: blue;

}

.element {

  color: var(–primary-color);

}

5. attr()

  • Purpose: Retrieves the value of an attribute.
  • Syntax: attr(attribute-name)

Example:

HTML

<div class=”element” data-color=”red”></div>

CSS

.element {

  background-color: attr(data-color);

}

6. env()

  • Purpose: Retrieves environment variables.
  • Syntax: env(variable-name)

Example:

CSS

.element {

  font-size: env(var(–font-size));

}

7. url()

  • Purpose: Specifies a URL.
  • Syntax: url(url)

Example:

CSS

.element {

  background-image: url(“image.jpg”);

}

Additional Tips

  • Combine functions: You can combine multiple functions to create complex expressions.
  • Test browser compatibility: Ensure that the functions you use are supported by your target browsers.
  • Use CSS preprocessors: Preprocessors like Sass or Less can provide additional features and syntax for working with functions.

By understanding and effectively using CSS functions, you can create more dynamic, flexible, and responsive web designs.

Specificities of Custom Properties | Custom Properties and CSS Functions
Looking at the min, max and clamp Functions of CSS | Custom Properties and CSS Functions

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?