Use syntax
First let’s look at an example:
html code:
<p class="element">这是一段文字</p>
css code:
.element { width:200px; height:200px; --main-bg-color: #000; color:#fff; background-color: var(--main-bg-color); }
Achievement effect:
The result is that the background of the DOM element becomes black.
The native variable definition syntax in CSS is: --*
, and the variable usage syntax is: var(--*)
, where *
represents our variable name. Regarding naming, various languages have some indications. For example, CSS selectors cannot start with a number, and variables in JS cannot be directly numerical. However, in CSS variables, these restrictions are not present, for example:
:root{ --main-bg-color: #000; }.element { background-color: var(--main-bg-color); }
Note: Variable names cannot contain
$, [, ^, (, %
and other characters, Ordinary characters are limited to "numbers [0-9]
" "letters [a-zA-Z]
" "underline_
" and "dash-
" These combinations, but can be Chinese, Japanese or Korean, for example:
##
.element { width:200px; height:200px; --黑色: #000; color:#fff; background-color: var(--黑色); }
Full syntax of css variables: The complete syntax used by CSS variables is:
var( [, ]? ), which in Chinese is: var(
##
.element { background-color: var(--new-bg-color,#EE0000); }
The result obtained is of course the background of the value of the following color
Let’s take a look at the variable name. What will happen if it is illegal? See the following example:
##body { --color: 20px; background-color: #369; background-color: var(--color, #cd0000); }
What is the background color of
at this time?A. transparent
- B. 20px
- C. #369
- D. #cd0000
- The answer is:
A. transparent CSS variable, it is found that the variable value is Illegal, for example, the background color above obviously cannot be 20px, then the default value of the background color, which is the default value, is used instead. Therefore, the above CSS is equivalent to:
body { --color: 20px; background-color: #369; background-color: transparent; }
Application of css variables in js
<p id="jsDom">这是一段文字</p>
css code:
#jsDom { --my-varwidth: 200px; background-color: #000; color:#fff; width:var(--my-varwidth); height:200px; }
js code:
##
var element = document.getElementById('jsDom');var curWidth = getComputedStyle(element).getPropertyValue("--my-varwidth"); console.log(curWidth); //200px//设置过后该DOM元素的宽度变为了300pxelement.style.setProperty("--my-varwidth", '300px');What if the style is written between lines? Then do the following:
html code:
<p id="jsDom" style="--my-varwidth:400px;width:var(--my-varwidth);">这是一段文字</p>js code:
var element = document.getElementById('jsDom');var curWidth = element.style.getPropertyValue("--my-varwidth"); console.log(curWidth); //400pxBrowser compatibility
The browser compatibility is as shown in the figure:
Speaking of which, I feel that this css variable is also very powerful. So compared with the preprocessor, which one do you think is better? Let’s talk about the disadvantages of preprocessors.
Preprocessor disadvantages
Preprocessor variables are not real-time
Perhaps surprising to newbies, the most common preprocessor limitation is that Sass cannot be used in media Define variables in the query or use @extend.
$gutter: 1em; @media (min-width: 30em) { $gutter: 2em; } .Container { padding: $gutter; }The above code will compile to:
.Container { padding: 1em; }As can be seen from the above results, the media query block is discarded, Variable assignments are ignored.
Since there is no way to vary variables based on matching @media rules, the only option is to assign a unique variable to each media query and write each variation individually.
Preprocessor variables cannot be cascaded
Whenever variables are used, scope problems inevitably arise. Should this variable be set as a global variable? Should it be scoped to files or modules? Should it be restricted to blocks?
Since the ultimate purpose of CSS is to add styles to HTML, it turns out that there is another effective way to scope variables: DOM elements. But since the preprocessors don't run in the browser and can't see the markup, they can't do this.
Suppose there is a website. For users who prefer larger text, add the class
# to the但同样,就像上面的媒体块示例,Sass完全忽略了该变量的赋值,这意味着这是不可能发生的。编译后的代码如下: 虽然继承严格说来是级联的一部分,之所以把它单独分出来讲,是因为多次想调用这个特性却不得。 假设一种情况,要在DOM元素上基于其父元素应用的颜色而设置样式: 上面的代码并不是有效的Sass(或CSS),但你应该明白它想达到什么目的。 最后一句声明试图在 显然这在 调用一个特定的用例:出于可访问性的原因,在继承了DOM属性上运行颜色函数是极其方便的。例如,确保文本始终可读,并充分与背景颜色形成鲜明对比。 有了自定义属性和新的CSS颜色函数,很快这将成为可能。 这是预处理器相对明显的一个缺点,提到它是因为我觉得它重要。如果你正使用 跨不同的工具集或CDN上托管的第三方样式表共享预处理器变量是不可能(或至少不容易)的。 原生的CSS自定义属性可以与任何CSS预处理器或纯CSS文件一起使用。反之则不然。 下面给一个css变量在媒体查询中的使用: 如果是预处理器这样写就无效了。 element.
##user-setting-large-text. When this class is set, larger $font-size variable assignments should be applied: $font-size: 1em;
.user-setting-large-text {
$font-size: 1.5em;
} body {
font-size: $font-size;
}
body {
font-size: 1em;
}
预处理器变量不继承
.alert {
background-color: lightyellow;
}.alert.info {
background-color: lightblue;
}.alert.error {
background-color: orangered;
}.alert button {
border-color: darken(background-color, 25%);
}
Sass中行不通
,因为预处理器不知道DOM结构
,但希望你清楚的认识到为什么这类东西是有用的。预处理器变量不可互操作
PostCSS
来构建网站,想使用只能通过Sass实现主题化的第三方组件,那你真是不走运了。:root {
--gutter: 1.5em;
}@media (min-width: 30em) {
:root {
--gutter: 2em;
}}
@media (min-width: 48em) {
:root {
--gutter: 3em;
}}
The above is the detailed content of Introduction to native variable var in CSS/CSS3. For more information, please follow other related articles on the PHP Chinese website!

@keyframesandCSSTransitionsdifferincomplexity:@keyframesallowsfordetailedanimationsequences,whileCSSTransitionshandlesimplestatechanges.UseCSSTransitionsforhovereffectslikebuttoncolorchanges,and@keyframesforintricateanimationslikerotatingspinners.

I know, I know: there are a ton of content management system options available, and while I've tested several, none have really been the one, y'know? Weird pricing models, difficult customization, some even end up becoming a whole &

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

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.

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.

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

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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools
