Talking about the use of CSS3 custom variables in projects from a project reconstruction

Talking about the use of CSS3 custom variables in projects from a project reconstruction

About CSS3 variables

When declaring a variable, add two hyphens ( -- ) before the variable name.

body{
    --color:red;
}

In the above code, a custom variable is declared in the body selector: --color .

It is no different from formal attributes such as color, except that it has no default meaning. So CSS variables are also called "CSS custom properties" - because variables and custom CSS properties are actually the same thing.
Furthermore, all kinds of values ​​can be 'put into' CSS variables, and CSS variables can be placed 'anywhere' .

Of course, there are a lot of similar introductions on the Internet, so let’s leave that aside for now and get to the point!

However, some basic applications, such as global universal color/size values, web page skinning, etc., will not be discussed in this article. You can explore them on your own.


Cause - Refactoring of "tabs"

I remember that in a project I did for a community website, there was a "tab" component for promotion:

show1

<div class="main-left-bottoms">
    <div id="tabs">
        <ul>
            <li class="on"><a name="anchor">Club activities</a></li>
            <li>Community Direction</li>
            <li>Message from the President</li>
            <li>Talent strategy</li>
        </ul>
        <div>
            <p>Since its establishment, YouC Club has held a large number of activities to enrich the extracurricular life of club members and achieve the goal of combining work and rest. Facts have proved that this is indeed effective. <br>
                For example,
            <ol>
                <li>On Mother's Day, we held <a href="http://www.50004.com/play52/fabebbfffcfa/XMzYwMzUwNjM4MA==/">
                    "Filial Piety·Mother's Day" event</a> (video loading may be a little slow) and achieved great success;</li>
                <li>During the winter solstice, we held a <a href="http://sfxy.nyist.edu.cn/info/1068/3802.htm">"Winter Solstice Dumpling Making" activity with the school and the dormitories. Everyone had a lot of fun.</li>
                <li>In our spare time, we also actively participated in the <a href="https://max.book118.com/html/2018/0513/166191393.shtm">"Visiting the Nursing Home" activity organized by the hospital, and had a great experience;</li>
            </ol>
        </div>
        <div class="hide">
            <p>&nbsp;&nbsp;YouC Studio was founded in 2009 and has a history of <span id="fffffyear"></span> years. <br>&nbsp;&nbsp;After these years of development, the community has produced talents in various fields, including PHP, Java, JavaWeb,
                Big data and so on. . . <font color="red">The current mainstream learning direction of this club is JavaWeb, that is, back-end implementation, which is more inclined towards website development. </font> <br>&nbsp;&nbsp;The community often completes the development of a project through corresponding exchange activities.
                In order to enhance their knowledge, members will occasionally participate in competitions and have achieved good results. <br><br>
                <font color="#ff7f50"> For specific personal plans, please scan the QR code on the right to ask seniors! </font></p>
        </div>
        <script>
            document.getElementById('fffffyear').innerHTML = (new Date().getFullYear() - 2009) + '';
        </script>
        <div class="hide">
            <br><br>
            <p>Although people are constantly joining and leaving, YouC is still here, waiting for you, and I firmly believe that the future of YouC will be even brighter! </p> <p>——President’s wish</p>
        </div>
        <div class="hide">
            <br>
            <p>Join us, join YouC. Here, you can have a wonderful knowledge experience. Seniors with great imaginations will lead you to explore knowledge, learn skills, carry out practical projects, and prepare for interviews. </font><br>
                Here, you can find happiness beyond your imagination! ! ! </p>
        </div>
    </div>
</div>
.main-left-bottoms{width: 100%;min-height: 280px;margin-top: 10px;}
.main-left-bottoms h1{color: orangered;font-style: italic;}
.main-left-bottoms #tabs{width: 99%;padding:5px;min-height: 280px;}
.main-left-bottoms #tabs ul{list-style:none;display:block;min-height:30px;line-height:30px;border-bottom:2px red solid;}
.main-left-bottoms #tabs ul li{cursor:pointer;float:left;list-style:none;height:28px;line-height:28px;margin:0 3px;border:2px groove orangered;border-bottom:none;display:inline-block;width:65px;text-align:center;font-weight: bold;color: black;padding: 0 10px;}
.main-left-bottoms #tabs ul li.on{border-bottom:2px solid skyblue;}
.main-left-bottoms #tabs div{min-height: 199px;line-height:25px;border-top:none;padding:0.3125em;overflow:hidden;}
#tabs div p{font-size: 0.838rem;}
#tabs div ol li{font-size: 0.875rem;margin-top: 5px;}
#tabs div ol li a{color: lightcoral;text-decoration: none;}
#tabs div ol li a:hover{color: orange;}
.main-left-bottoms .hide{display:none;}

Then use JS to add the class name hide to the (same level) elements outside the div click element. It's very simple.

Later, as I learned more and paid more and more attention to "user experience", I thought: What if the browser could "remember" where the user browsed before exiting, whether it was a page, tab or list? That would be great.
So I tried to use ajax to assist the browser state list to achieve the switching and saving effect on the entire page (click here). This is indeed a good method, but after I gradually launched the CSS series of articles, I became more "greedy": Can I achieve this effect without JavaScript? —— ::target !

(I will publish a special article to discuss this later, it would be a bit too much to mention it here...)


Later, CSS3 introduced the "custom variable" attribute. It happened that the official website page was reconstructed with Vue, so I thought about using CSS3 variables to redo this part:

CSS3 variables to achieve tab switching

show2

The seemingly smooth tab switching effect above is actually very simple (completed using vue+scss):
You should know: There are 3 APIs in JS for style operation variables

  • Read variables: elem.style.getPropertyValue()
  • Set variables: elem.style.setProperty()
  • Remove a variable: elem.style.removeProperty()
<div class="tab-navbar">
    <nav>
        <a v-for="(v, i) in list" :key="v" :class="{ active: index === i }" @click="select(i)">Title{{i + 1}}</a>
    </nav>
    <div>
        <ul ref="tabs" :style="`--tab-count: ${list.length}`">
            <li v-for="(v, i) in list" :key="v" :style="`--bg-color: ${v}`">I am the content {{i + 1}}</li>
        </ul>
    </div>
</div>
.tab-navbar {
    display: flex;
    overflow: hidden;
    border-radius: 10px;
    width: 300px;
    height: 200px;
    nav {
        display: flex;
        height: 40px;
        background-color: #f0f0f0;
        line-height: 40px;
        text-align: center;
        a {
            flex: 1;
            cursor: pointer;
            transition: all 300ms;
            &.active {
                background-color: #3c9;
                color: #fff;
            }
        }
    }
    div {
        flex: 1;
        ul {
            --tab-index: 0;
            --tab-width: calc(var(--tab-count) * 100%);
            --tab-move: calc(var(--tab-index) / var(--tab-count) * -100%);
            display: flex;
            flex-wrap: nowrap;
            width: var(--tab-width);
            height: 100%;
            transform: translate3d(var(--tab-move), 0, 0);
            transition: all 300ms;
        }
        li {
            display: flex;
            justify-content: center;
            align-items: center;
            flex: 1;
            background-color: var(--bg-color);
            font-weight: bold;
            font-size: 20px;
            color: #fff;
        }
    }
}

Define --tab-index on <ul> to indicate the current index of the Tab. When the button is clicked, the value of --tab-index is reset, so that the specified Tab can be displayed without moving the position of <ul> in the DOM. The reason why <ul> can be moved without operating DOM is because --tab-move is defined. The relationship between --tab-index and --tab-move is calculated through calc() , thereby manipulating transform:translate3d() to move <ul> .

export default {
    data() {
        return {
            index: 0,
            list: ["#09f", "#f90", "#66f", "#f66"]
        };
    },
    methods: {
        select(i) {
            this.index = i;
            this.$refs.tabs.style.setProperty("--tab-index", i);
        }
    }
};

In addition, defining --bg-color on <li> to represent the background color of the Tab is also a relatively concise way of template assignment, which is always better looking than writing <li :style="backgroundColor:${color}"> - if multiple attributes depend on a variable assignment, then it is more convenient to use the variable to assign to the style. Those attributes can be calculated and assigned in the CSS file, which can help JS share some attribute calculation work and greatly improve rendering performance.


I think the above case is definitely not enough to satisfy you, so:

CSS3 custom variables to achieve 'alternative' loading bar

show3

<ul class="strip-loading">
	<li style="--line-index: 0"></li>
	<li style="--line-index: 1"></li>
	<li style="--line-index: 2"></li>
	<li style="--line-index: 3"></li>
	<li style="--line-index: 4"></li>
	<li style="--line-index: 5"></li>
</ul>

.strip-loading {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 200px;
    height: 200px;
    li {
        --time: calc(var(--line-index) * 200ms);
        border-radius: 3px;
        width: 6px;
        height: 30px;
        background-color: #f66;
        animation: beat 1.5s ease-in-out var(--time) infinite;
        & + li {
            margin-left: 5px;
        }
    }
}
@keyframes beat {
    0%,
    100% {
        transform: scaleY(1);
    }
    50% {
        transform: scaleY(.5);
    }
}

The var() calculation function is used with custom variables as the delay of the animation, so that each element has its "own" delay time - CSS3 variables greatly simplify the code redundancy caused by :nth-child(N) in the previous CSS.


Cool mouse tracking effects

Coincidentally, before I wrote this article, a senior from the backend of a community suggested making a cool button to replace the original submit button:

low

The effect after the change is probably like this:

show4

Actually, the background color of the "first version" used linear-gradient+animation+hue-rotate, but the senior said it was too fancy... Hehe, you can try it.

In fact, the idea is relatively simple. First, lay out and color the buttons, then use pseudo-elements to mark the position of the mouse, define --x and --y to represent the coordinates of the pseudo-elements in the button, use JS to get the offsetX and offsetY of the mouse on the button and assign them to --x and --y respectively, and then add a radial gradient background color to the pseudo-element, and you're done. A cool mouse hover tracking effect is created.

<button class="track-btn">
	<span>Young man, click me and I will give you strength</span>
</button>
.track-btn {
	margin: 0;
	padding: 0;
	/*Custom border*/
	border: 0;
	/*Eliminate the default blue border effect when clicking*/
	outline: none;
	-webkit-appearence: none;
	overflow: hidden;
	position: relative;
	border-radius: 25px;
	height: 49.9px;
	background-color: #66f;
	cursor: pointer;
	line-height: 50px;
	text-align: center;
	font-weight: bold;
	font-size: 18px;
	color: #fff;
	padding: 0 20px;
	span {
		position: relative;
		pointer-events: none;
	}
	&::before {
		--size: 0;
		position: absolute;
		left: var(--x);
		top: var(--y);
		width: var(--size);
		height: var(--size);
		background-image: radial-gradient(circle closest-side, #09f, transparent);
		content: "";
		transform: translate3d(-50%, -50%, 0);
		transition: width 200ms ease, height 200ms ease;
	}
	&:hover::before {
		--size: 200px;
	}
}
const btn = document.getElementsByClassName("track-btn")[0];

btn.addEventListener("mousemove", e => {
	btn.style.setProperty("--x", `${e.offsetX}px`);
	btn.style.setProperty("--y", `${e.offsetY}px`);
});

You can also add even more awesome animations on top of this!


Reality & Prospects

As mentioned before: you can put CSS3 variables anywhere - in fact, even the "less well-known" ::root can be used as a "pure land" to store variables separately.

//Reference/modify the css3 variable value in style document.documentElement.style.setProperty("name", value)

It is worth noting that if you want to modify custom variables in CSS, it is currently recommended to put them in the same "target"! for example:

#angular {
	--angular: "";
}
#angular:checked {
	 --angular: "angular";
}

Most websites today define default spacing between items in a layout, as well as default padding, font sizes, and even typography layouts for all the different sections on the page based on page responsiveness. But many times, we can only switch between different "external link CSS files" or change all corresponding property values ​​in a small range. But this will lead to one thing: before reaching the "next media critical value", there will always be some "accidental" distances, such as: within a certain range of document.documentElement.clientWidth || document.body.clientWidth; the spacing between elements will be large, but on smaller screens the space is not enough to accommodate too much blank space and before or after that, the spacing will "suddenly change".

:root { 
	--size: 1.5em; 
} 
@media (min-width: 30em) { 
	:root { 
		--size: 2em; 
	} 
} 
.Container {
	margin: 0 auto; 
	max-width: 60em; 
	font-size: var(--size); 
}

We can also listen to the resize page size changes in js to change the value of --size in real time. The more variables there are, the more code can be saved. —— In the past, this could only be achieved by introducing the scss / less library.

Custom properties fill the gap in scss/less where preprocessor variables cannot be used correctly in some scenarios. However, whether from the perspective of compatibility or current development, using preprocessor variables is still a more elegant choice in many cases. It’s likely that many sites will continue to use a combination of both for some time: custom properties for dynamic themes, and preprocessor variables for static templates.

This concludes this article about how to use CSS3 custom variables in a project starting from a project reconstruction. For more information about the use of CSS3 custom variables in projects, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

<<:  Detailed explanation of using echarts map in angular

>>:  Introduction to the process of installing MySQL 8.0 in Linux environment

Recommend

How to implement web page compression in Nginx optimization service

Configure web page compression to save resources ...

Vue implements adding watermark to uploaded pictures

This article shares the specific implementation c...

MySQL column to row conversion tips (share)

Preface: Because many business tables use design ...

Detailed explanation of two points to note in vue3: setup

Table of contents In vue2 In vue3 Notes on setup ...

The difference between name and value in input tag

type is the control used for input and output in t...

HTML form tag usage learning tutorial

Forms in HTML can be used to collect various type...

Solutions for high traffic websites

First: First, confirm whether the server hardware ...

Analysis of slow insert cases caused by large transactions in MySQL

【question】 The INSERT statement is one of the mos...

Native JavaScript to implement random roll call table

This article example shares the specific code of ...

XHTML Getting Started Tutorial: XHTML Hyperlinks

It is no exaggeration to say that hyperlinks conne...

Detailed explanation of the principle of creating tomcat in Eclipse

When creating a tomcat server on a local eclipse,...

50 Beautiful FLASH Website Design Examples

Flash enabled designers and developers to deliver...

SQL Practice Exercise: Online Mall Database User Information Data Operation

Online shopping mall database-user information da...