分享兴趣,传播快乐,增长见闻,留下美好!
亲爱的您,这里是LearningYard新学苑。
今天小编为大家带来
“学越千山:CSS技巧——CSS变量与颜色编码”
欢迎您的访问。
Share interest, spread happiness, increase knowledge, and leave beautiful.
Dear, this is the LearingYard Academy!
Today, the editor brings the
Learning over a thousand mountains:CSS Techniques—CSS Variables & Color Codes,
Welcome to visit!
思维导图
Mind mapping
一、颜色表示方式
Color Representation Methods
十六进制颜色(Hexadecimal Colors)
组成字符:0-9 和 A-F(A=10,F=15)
Characters used: 0-9 and A-F (A=10, F=15)
格式:#RRGGBB(如 #FF0000 表示红色)
Format: #RRGGBB (e.g., #FF0000 = red)
缩写规则:当每对字符相同时可缩写为 3 位(如 #F00 → #FF0000)
Shorthand notation: When pairs are identical, abbreviate to 3 digits (e.g., #F00 → #FF0000)
亮度规则:0(无颜色)→ F(最高亮度)
Brightness rules: 0 (no color) → F (maximum brightness)
RGB 颜色(RGB Colors)
格式:rgb(红, 绿, 蓝)
Format: rgb(red, green, blue)
数值范围:0-255(对应十六进制的 00-FF)
Value range: 0-255 (corresponding to 00-FF in hex)
示例:rgb(255, 0, 0) 表示红色
Example: rgb(255, 0, 0) = red
二、CSS 变量
CSS Variables
1、定义变量(Defining Variables)
:root {
--main-color: #FF0000; /* 全局变量 */
}
.element {
--secondary-color: #00F; /* 局部变量 */
}
2、使用变量(Using Variables)
.box {
color: var(--main-color);
background: var(--secondary-color, blue); /* 备用值为 blue */
}
3、变量特性(Variable Characteristics)
继承性:子元素继承父元素的变量(除非被覆盖)
Inheritance: Child elements inherit variables from parent elements (unless overridden).
作用域::root 中定义的变量全局有效,局部变量只在选择器内有效
Scope: Variables defined in :root are global; local variables are selector-specific.
动态更新:可通过 JavaScript 实时修改变量值
Dynamic Updates: Values can be modified in real-time via JavaScript.
三、实际应用技巧
Practical Techniques
1、主题切换示例(Theme Switching Example)
:root {
--primary-color: coral;
--text-color: black;
}
.dark-theme {
--primary-color: darkred;
--text-color: white;
}
2、JavaScript 动态修改(Dynamic Modification with JavaScript)
// 修改全局变量
document.documentElement.style.setProperty('--primary-color', 'green');
四、注意事项
Key Considerations
变量名区分大小写(--Color ≠ --color)
Case Sensitivity: Variable names are case-sensitive (--Color ≠ --color).
推荐命名规范(如 --primary-color)
Naming Convention: Use semantic names (e.g., --primary-color).
合理使用备用值增强兼容性
Fallback Values: Enhance compatibility with fallbacks (e.g., var(--color, red)).
今天的分享就到这里了,
如果您对文章有独特的想法,
欢迎给我们留言。
让我们相约明天,
祝您今天过得开心快乐!
That's all for today's sharing.
If you have a unique idea about the article,
please leave us a message,
and let us meet tomorrow.
I wish you a nice day!
翻译:百度翻译
参考资料:百度百科,CSDN
本文由LearningYard新学苑整理并发出,如有侵权请后台留言沟通。

优网科技秉承"专业团队、品质服务" 的经营理念,诚信务实的服务了近万家客户,成为众多世界500强、集团和上市公司的长期合作伙伴!
优网科技成立于2001年,擅长网站建设、网站与各类业务系统深度整合,致力于提供完善的企业互联网解决方案。优网科技提供PC端网站建设(品牌展示型、官方门户型、营销商务型、电子商务型、信息门户型、DIY体验、720全景展厅及3D虚拟仿真)、移动端应用(手机站、APP开发)、微信定制开发(微信官网、微信商城、企业微信)、微信小程序定制开发等一系列互联网应用服务。