search
HomeWeb Front-endCSS TutorialImplementation of css custom properties and spotlight effects (code)

The content this article brings to you is about the implementation (code) of CSS custom properties and spotlight effects. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Introduction

CSS Variables, a thing that is not so new, but is definitely a revolution for css.

When using variables before, we needed to use preprocessing tools such as sass and less. Now we can directly use css to declare variables.

Compatibility

Old rules, let’s look at compatibility first

Implementation of css custom properties and spotlight effects (code)

Compatibility is green and red Aren't there two more? How can you stick to small details when doing big things? Just let it go.

Syntax

The syntax is a bit ugly but very simple, --* to declare variable names, var(--*) to use, maybe You have to ask, why use -- instead of $? Well, isn’t that what sass and less are used for?

Declaration and use must be placed in the {} code block

body{
    --bg-color: lightblue;
    background-color: var(--bg-color);
}

Implementation of css custom properties and spotlight effects (code)

The code is very simple, you can see the effect directly, so I won’t go into details. .

Global variables and variable coverage

The variables declared in the :root code block are global variables, and local variables will overwrite global variables

:root{
    --bg-color: red;
}
body{
    --bg-color: lightblue;
    background-color: var(--bg-color);
}

The last thing that takes effect is --bg-color: lightblue, and the value of the bg-color variable becomes the lightblue

variable. Default value

The complete variable uses the syntaxvar( [, ]? ). When the variable is not defined, the following value will be used. Look at the example below

body{
--1: red;
color:var(--2, blue);
}

The above code will search for the --2 variable in the scope of body. If not, it will search the global. If there is none, it will Use the latter value, so the final color that takes effect is blue

As you can see, our variable names directly use numbers above. CSS variables are very easy to use. Not only numbers, but also Chinese characters are acceptable.

Participate in calculation

:root{
    --bg-color: lightblue;
    --文字颜色: white;
    --fong-size: 30;
}
body{
    background-color: var(--bg-color);
}
div{
    color: var(--文字颜色);
    font-size: var(--fong-size)px;
}

What is the size of the text in p at this time? It is the default size of the browser. Why is it not 30px as we imagined? This is because there will be a space at the end when the variable is converted. var(--fong-size)px will be converted to 30 px

We can honestly declare the variable with the unit

--fong-size: 30px;

or use calc() to calculate the attribute

 font-size: calc(var(--fong-size) * 1px);

Implementation of css custom properties and spotlight effects (code)

js acquisition and assignment

We can use js to obtain and assign css variables. Look, it’s very convenient, old iron.

:root{
     --bg-color: lightblue;
}

 // 获取
getComputedStyle(document.documentElement).getPropertyValue('--bg-color')  // lightblue
        
 // 赋值
document.documentElement.style.setProperty('--bg-color', 'yellowgreen')

Simple application

Above we introduced the declaration and use of css variables and the use of js to obtain and assign values. Next, we completed a spotlight effect (I made it blindly , I don’t know what it should be called), No, it looks like this. The GIF image is a bit stuck, please wait and see

Implementation of css custom properties and spotlight effects (code)

Before writing the code, let’s sort out the ideas and how to achieve this effect. The main ones are as follows A few steps
1. Declare global css variables
2. Set the body to a pure black background, add p and set the background image
3. Use clip-path for the background image of p Crop, use variables to set the center position of the circle
4. Add mouse events, dynamically change the css variable which is the center position of the circle

Then start writing code

The layout is very simple, it is just a div, we Mainly talk about the css style

:root{
    --x: 40;
    --y: 40;
}
*{
    padding: 0;
    margin: 0;
}
body{
    width: 100vw;
    height: 100vh;
    background: #000;
}
div{
    width: 100%;
    height: 100%;
    background: url('../images/bg.png') 0 0 no-repeat;
    clip-path: circle(100px at calc(var(--x) * 1px ) calc(var(--y) * 1px));
    background-size: cover;
}

Use the * wildcard to simply and crudely remove the browser default style. The body is set to 100%. Here we use vw and vh unit means dividing the viewport into 100 equal parts. 100vw means that 100 parts of width are 100% wide, vh is the same.

Here’s the point, use css to declare two variables --x and --y, and then use them when cropping in the p style clip-path: circle(100px at calc(var(--x) * 1px ) calc(var(--y) * 1px)), we use clip-path to crop A circle is drawn, its syntax is as follows

clip-path: circle(半径 at 圆心X轴坐标 圆心Y轴坐标 )

At this time, such a circle is displayed on the page

Implementation of css custom properties and spotlight effects (code)

The last step is, We add the mouse follow event and change the values ​​​​of --x and --y

document.addEventListener('mouseover', function(e){
     document.documentElement.style.setProperty('--x', e.clientX)
     document.documentElement.style.setProperty('--y', e.clientY)
 })

At this time, we use css variables to complete a simple effect, css There are more usage scenarios for variables, please feel free to use them.

For detailed code, please move to github

小结

1、可以嵌套使用

:root{
    --green: green;
    --bgcolor: var(--green);
}

2、变量的不合法

div {
  --color: 10px;
  background-color: yellow;
  background-color: var(--color, green);
}

此时p的背景色是什么呢?

A rgba(0,0,0,0)  B 10px  C yellow  D green

答案是 A

简单来说是变量声明的时候不是合法的,背景色显然不能是10px,所以浏览器就会使用默认值,这个默认值并不是使用变量的默认值,是浏览器自己的默认值
background-color: var(--color, green)就会变成background-color: rgba(0,0,0,0)

相关推荐:

jquery实现聚光灯效果的方法_jquery

CSS实现图片动态效果的相关属性介绍

The above is the detailed content of Implementation of css custom properties and spotlight effects (code). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
CSS Flexbox vs Grid: a comprehensive reviewCSS Flexbox vs Grid: a comprehensive reviewMay 12, 2025 am 12:01 AM

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

How to Include CSS Files: Methods and Best PracticesHow to Include CSS Files: Methods and Best PracticesMay 11, 2025 am 12:02 AM

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor