1. Variables are dynamically presented as characters
CSS var variables (CSS custom attributes) are very useful. Then, sometimes, these variables are needed to be displayed on the page as characters at the same time. What we think of is to use ::before/::after
pseudo-elements with content
attributes, but to use CSS variables directly as content
attribute values No effect.
E.g:
/* invalid*/ .bar::before { content: var(--percent); }
How should it be presented?
2. Use CSS counter to present CSS var variable value
The schematic code is as follows:
/* Effective*/ .bar::before { counter-reset: progress var(--percent); content: counter(progress); }
That is, although the content
attribute itself does not support variables, the counter-reset
initial value of the counter behind the attribute is supported, so we can take a trick to make the CSS var variable value displayed as a character on the page.
If you don’t know much about CSS counters, you can refer to my previous article: " CSS counter (content directory number auto-increment) detailed explanation ".
Three, actual application case display
For example, we need to implement a progress bar effect. The width percentage value of the loaded part is the same as the progress value. It is best to control it through a variable, which will greatly simplify our implementation.
At this time, CSS var variables are very suitable for use.
For example, the effect shown in the figure below:
The HTML structure is very simple, just a single tag without any nesting:
<label>Picture 1:</label> <div class="bar" style="--percent: 60;"></div> <label>Picture 2:</label> <div class="bar" style="--percent: 40;"></div> <label>Picture 3:</label> <div class="bar" style="--percent: 20;"></div>
The key is CSS, here is the CSS variable value rendering technique used here, see the red highlighted part of the code below:
.bar { height: 20px; width: 300px; background-color: #f5f5f5; } .bar::before { display: block; counter-reset: progress var(--percent); content: counter(progress) '%\2002'; width: calc(1% * var(--percent)); color: #fff; background-color: #2486ff; text-align: right; white-space: nowrap; overflow: hidden; }
You can click here: CSS percentage variable and progress bar demo
Fourth, a little conclusion
Although it is a small trick, it is very practical. I have used it many times in the project so far. Writing this article is also convenient for you to find it quickly. When you actually use it, just copy the code and change the variable name.
To start with, if you encounter other scenes that require dynamic display of variables, you can also try this presentation technique in this article. You don't have to remember now, as long as you have an impression, you can find this article by going to my blog and searching for " CSS variables " or directly searching for " var ".
Well, what I want to say, thanks for reading, and welcome to communicate.