This is the 16th day of my participation in Gwen Challenge

This article is a compilation of the content and does not guarantee that the content is up to date. Stay tuned for updates.


Link to Original English

CSS Function

Like many programming languages (is CSS a programming language?) CSS has a set of built-in functions. In this article, you will learn about functions and how to use them.

What is a function?

A function is a self-contained piece of code that accomplishes a specific task. Functions allow you to specify one or a set of arguments that are passed into the function when called. This set of parameters is called pass parameters.

CSS functions are mostly pure functions. This means that if you call with the same parameters, you will get the same result. You don’t care what happens inside the function. Function values are usually recalculated as CSS values change, such as currentColor.

You can’t write your own CSS functions yet (Houdini aside).

CSS functions can be nested with each other in some cases for greater flexibility.

Function selector

.post :is(h1.h2.h3) {
    line-height: 1.2;
}
Copy the code

The arguments passed to these functions are CSS selectors. The selector will be evaluated. If it matches the element, the following CSS rules are used

Custom attributes and var()

:root {
    --base-color: #ff00ff;
}

.my-element {
    background: var(--base-color);
}
Copy the code

A custom property is a variable that allows you to mark values in YOUR CSS code. Custom properties are also affected by cascades, which means they can be contextually manipulated or redefined. Custom attributes must be prefixed with two dashes and case-sensitive.

.my-element {
    background: var(--base-color, hotpink);
}
Copy the code

Var supports fallback. When the first parameter value is invalid, it falls back to the default value represented by the second parameter. In the example above, fallback the background color

The ability to return values

This function only performs operations on the return value. Examples are attr() and URL (). You pass in one or more parameters and use them to the right of the CSS declaration.

a::after {
  content: attr('href');
}
Copy the code

The function here is to set the contents of the element attributes as pseudo-elements. If the value of an element attribute changes, it is automatically reflected in the attribute.

.my-element {
    background-image: url('/path/to/image.jpg');
}
Copy the code

This function requires a string URL to load images, fonts, and content. If a valid URL cannot be passed or the resource to which the URL points cannot be found, anything is returned via this feature.