CSS Variables for Front-end Basics#
Let's demonstrate how to use them.
First, create a square.
We notice that the width and height are the same, and the code is repetitive.
Repetitive code will definitely cause inconvenience in maintenance. My code is relatively small, so you may not feel it, but when the code becomes larger, it will be very troublesome to maintain.
How do we write CSS variables? --variableName: value
For example:
--size: 300px;
When calling it later:
width: var(--size)
When we want to change the width and height of the square, we just need to change the value of --size.
Variables can be inherited like CSS properties, so if there is a variable that needs to be used throughout the webpage, it can be written in HTML or .
Since it is a variable, we can also participate in calculations.
To make it look convenient, let's create a child div.
We want to make the padding of the box 20% of the width, so we can write it like this:
padding:calc(var(--size) * 0.2)
Make the width and height of the child element half of the parent element.
Change the parent element to 100px.
No problem.
Used to write global themes.
Although the theme color is the same, the transparency is different in different places.
Change the transparency of the theme color. Use three RGB values as variables, and adjust the transparency with RGBA. If you want to preview the color, you can use comments.
If multiple elements have the same animation but different sizes, so the offset is also different, then you need to write multiple animations.
Just set a CSS variable on each element and call it in the animation.
<div class="box" style="--dotsize: 10px"></div>
<div class="box" style="--dotsize: 5px"></div>
transform:translate(calc(var(--dotsize) * 3),calc(var(--dotsize) - 3))
Okay, that's all for now. Explore more usage on your own and I wish you all become proficient in CSS soon.