目錄
✅ What Are CSS Custom Properties?
? Why Use Them Over Sass/Less Variables?
? Practical Use Cases
1. Theme Switching
2. Component-Level Variables
3. Responsive Design
⚠️ Common Pitfalls & Tips
?️ Bonus: JavaScript Integration
首頁 web前端 H5教程 CSS自定義屬性的完整指南(變量)

CSS自定義屬性的完整指南(變量)

Aug 01, 2025 am 05:58 AM

CSS Custom Properties(CSS變量)是原生、動態且可被JavaScript操作的樣式值,用於替代重複的CSS值並實現主題切換、組件隔離和響應式設計。 1. 聲明在:root中定義全局變量(如--primary-color: #3498db),用var()函數調用(如background-color: var(--primary-color));2. 支持級聯與繼承,可在組件或媒體查詢中覆蓋(如@media中修改--gap);3. 可通過JavaScript動態更新(如document.documentElement.style.setProperty('--primary-color', 'hotpink')),無需重新編譯,適用於主題切換、用戶偏好設置及動畫交互。注意使用kebab-case命名、提供備用值(如var(--text, black))並避免循環引用。

CSS Custom Properties—often called CSS variables—are a powerful feature that let you store and reuse values across your stylesheets. Unlike preprocessor variables (like in Sass), they're native to CSS, dynamic , and can be manipulated with JavaScript. If you've ever repeated the same color or spacing value dozens of times in your CSS, custom properties are your solution.

Here's everything you need to know—from basics to advanced use cases.


✅ What Are CSS Custom Properties?

Custom properties are declared using a double dash ( -- ) prefix:

 :root {
  --primary-color: #3498db;
  --spacing: 1rem;
}
  • :root is the best place to define global variables (applies to all elements).
  • You access them using the var() function:
 .button {
  background-color: var(--primary-color);
  padding: var(--spacing);
}

They cascade and inherit , just like regular CSS properties—so you can override them per component or media query.


? Why Use Them Over Sass/Less Variables?

Feature Sass Variables CSS Custom Properties
Dynamic updates ❌ No ✅ Yes (via JS or :hover )
Cascade/inherit ❌ No ✅ Yes
Scope control ❌ File-level only ✅ Element-level
Runtime changes ❌ Compile-time only ✅ Real-time

Example: change theme on button click with JS:

 document.documentElement.style.setProperty('--primary-color', 'hotpink');

? Instant visual update—no recompilation needed.


? Practical Use Cases

1. Theme Switching

Store theme values in :root , then swap them on demand:

 :root {
  --bg: #fff;
  --text: #333;
}

[data-theme="dark"] {
  --bg: #222;
  --text: #f5f5f5;
}

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

Toggle via JS:

 document.body.dataset.theme = 'dark';

2. Component-Level Variables

Isolate styles for reusable components:

 .card {
  --card-padding: 1.5rem;
  --card-border: 1px solid #ddd;

  padding: var(--card-padding);
  border: var(--card-border);
}

Now each .card instance can override its own padding or border without affecting others.

3. Responsive Design

Use media queries to change variables—not entire rules:

 :root {
  --gap: 1rem;
}

@media (min-width: 768px) {
  :root {
    --gap: 2rem;
  }
}

.grid {
  gap: var(--gap); /* Automatically updates */
}

Cleaner than rewriting every gap declaration per breakpoint.


⚠️ Common Pitfalls & Tips

  • Always provide fallbacks in case a variable is undefined:

     color: var(--text, black); /* black if --text not set */
  • No camelCase —stick to kebab-case ( --main-color , not --mainColor ).

  • Avoid circular references —this will break:

     --a: var(--b);
    --b: var(--a); /* ? Infinite loop */
  • Use in animations? Yes—but only if the property supports interpolation (like opacity , not display ).


?️ Bonus: JavaScript Integration

Read and write custom properties easily:

 // Read
getComputedStyle(document.documentElement)
  .getPropertyValue('--primary-color');

// Write
document.documentElement.style.setProperty('--primary-color', 'purple');

Use this for:

  • User preferences (theme, font size)
  • A/B testing UI variants
  • Animating values with JS (eg, parallax effects)

That's it!
CSS custom properties aren't just about DRY code—they enable dynamic, maintainable, and interactive styles. Start small: replace repeated colors or spacing values. Then scale up to full theming or responsive logic.

No build step. No dependencies. Just modern, native CSS.

以上是CSS自定義屬性的完整指南(變量)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

HTML5解析器如何處理錯誤? HTML5解析器如何處理錯誤? Aug 02, 2025 am 07:51 AM

HTML5parsershandlemalformedHTMLbyfollowingadeterministicalgorithmtoensureconsistentandrobustrendering.1.Formismatchedorunclosedtags,theparserautomaticallyclosestagsandadjustsnestingbasedoncontext,suchasclosingabeforeaandreopeningitafterward.2.Withimp

什麼是HTML5數據屬性? 什麼是HTML5數據屬性? Aug 06, 2025 pm 05:39 PM

HTML5dataattributesarecustom,validHTMLattributesusedtostoreextrainformationinelementsforJavaScriptorCSS.1.Theyaredefinedasdata-*attributes,likedata-user-id="123".2.Theyallowembeddingprivate,customdatadirectlyinmarkupwithoutaffectinglayoutor

HTML5中的局部元素是什麼? HTML5中的局部元素是什麼? Aug 12, 2025 pm 04:37 PM

thelementshouldshouldsbousedforcontenttangentytothemaincontent,SustAssidebars,pullquotes,定義,廣告,orrelelatedLinks; 2. ItcanbeplectlaceDinSideSideRoutsIdeAnartIcleDeAlticleDepledePonconTeptOncontendementement; 3.Seasemanticemanticelementthatenhancesacaccccccccccccccccceedibilityancibilityandseobypyandseobyp.Anderancebyp.And.anceScebibilibilyandseobyp

如何處理HTML5畫布上的鼠標事件? 如何處理HTML5畫布上的鼠標事件? Aug 02, 2025 am 06:29 AM

要正確處理HTML5canvas上的鼠標事件,首先需給canvas添加事件監聽器,然後計算鼠標相對於canvas的坐標,接著通過幾何檢測判斷是否與繪製的對象交互,最後實現如拖拽等交互模式。 1.使用addEventListener為canvas綁定mousedown、mousemove、mouseup和mouseleave事件;2.利用getBoundingClientRect方法將clientX/clientY轉換為相對於canvas的坐標;3.通過手動幾何計算(如矩形邊界或圓的距離公式)檢測鼠

如何在HTML5中依次播放多個音頻文件? 如何在HTML5中依次播放多個音頻文件? Aug 25, 2025 pm 03:08 PM

可以通過監聽HTML5音頻元素的ended事件來依次播放多個音頻文件,首先明確答案是使用ended事件觸發下一個音頻播放;具體步驟為:1.定義音頻文件數組並獲取audio元素;2.設置當前播放索引,加載並播放首個音頻;3.為audio元素綁定ended事件,在事件觸發時遞增索引並加載下一個音頻;4.可選擇實現循環播放或播放結束後停止;5.可預加載下一個音頻以提升體驗;6.添加錯誤處理以跳過失敗的音頻;7.注意瀏覽器autoplay限制,需由用戶交互觸發首次播放,確保後續播放不被阻止,整個過程通過

HTML5中的可讀性屬性是什麼? HTML5中的可讀性屬性是什麼? Aug 08, 2025 am 11:55 AM

ThereadonlyattributeinHTML5makesforminputsnon-editablewhilestillallowingsubmissionanduserinteraction;1.Itappliestoandelements;2.Itisabooleanattribute,soonly"readonly"needstobepresent;3.Unlike"disabled",itallowsfocusandthedataisinc

HTML5中支持的音頻格式是什麼? HTML5中支持的音頻格式是什麼? Aug 05, 2025 pm 08:29 PM

HTML5音頻格式支持因瀏覽器而異,最常用格式包括:1.MP3(.mp3,audio/mpeg,所有主流瀏覽器均支持,兼容性最佳);2.WAV(.wav,audio/wav,支持較好但文件大,適合短音頻);3.OGG(.ogg/.oga,audio/ogg,Chrome、Firefox、Opera支持,Safari和IE不支持,開源免費);4.AAC(.aac/.m4a,audio/aac,Safari、Chrome、Edge支持,Firefox支持有限,常用於蘋果設備)。為確保兼容性,應在標籤

如何創建簡單的HTML5網頁 如何創建簡單的HTML5網頁 Aug 12, 2025 am 11:51 AM

創建一個簡單的HTML5網頁需要先使用聲明文檔類型,接著構建包含、和的基本結構,其中內設置字符編碼、視口和標題,內添加可見內容如標題、段落、鏈接、圖片和列表,保存為.html文件後即可在瀏覽器中直接打開查看,無需服務器支持,這是一個完整且有效的HTML5頁面的基礎。

See all articles