CSS条件语句
外观
CSS条件语句[编辑 | 编辑源代码]
CSS预处理器(如Sass、Less和Stylus)通过引入条件语句(Conditional Statements)扩展了原生CSS的功能,允许开发者根据特定条件动态生成样式。本条目将详细解释CSS预处理器的条件语句概念、语法和实际应用。
概述[编辑 | 编辑源代码]
条件语句是编程中的基础结构,用于基于不同条件执行不同的代码块。在CSS预处理器中,条件语句使样式表具备逻辑判断能力,例如:
- 根据主题变量切换颜色
- 响应不同浏览器前缀
- 控制混合宏(Mixins)的输出
主要预处理器的条件语句实现方式:
- Sass/Less:
@if
,@else if
,@else
- Stylus:
if
,else if
,else
语法详解[编辑 | 编辑源代码]
Sass 示例[编辑 | 编辑源代码]
$theme: 'dark';
.button {
@if $theme == 'dark' {
background: black;
color: white;
} @else if $theme == 'light' {
background: white;
color: black;
} @else {
background: gray;
color: blue;
}
}
输出CSS:
.button {
background: black;
color: white;
}
Less 示例[编辑 | 编辑源代码]
@size: large;
.text {
& when (@size = large) {
font-size: 24px;
}
& when (@size = medium) {
font-size: 16px;
}
& when (@size = small) {
font-size: 12px;
}
}
输出CSS(当@size: large
时):
.text {
font-size: 24px;
}
逻辑运算符[编辑 | 编辑源代码]
预处理支持以下逻辑运算符:
运算符 | 描述 | 示例 |
---|---|---|
== |
等于 | @if $var == 10
|
!= |
不等于 | @if $var != red
|
> |
大于 | @if $width > 100px
|
and |
逻辑与 | @if $a and $b
|
or |
逻辑或 | @if $x or $y
|
not |
逻辑非 | @if not $flag
|
实际应用案例[编辑 | 编辑源代码]
响应式断点控制[编辑 | 编辑源代码]
@mixin respond-to($breakpoint) {
@if $breakpoint == phone {
@media (max-width: 600px) { @content; }
} @else if $breakpoint == tablet {
@media (max-width: 900px) { @content; }
} @else if $breakpoint == desktop {
@media (min-width: 901px) { @content; }
}
}
.header {
font-size: 2rem;
@include respond-to(phone) {
font-size: 1.5rem;
}
}
主题切换系统[编辑 | 编辑源代码]
对应Sass实现:
@mixin theme-colors($theme) {
@if $theme == 'dark' {
background: #333;
color: #fff;
} @else {
background: #fff;
color: #333;
}
}
body {
@include theme-colors('dark');
}
高级用法[编辑 | 编辑源代码]
在循环中使用条件[编辑 | 编辑源代码]
for $i in 1..12
.col-{$i}
width: (100% / $i)
@if $i > 6
font-size: 14px
@else
font-size: 16px
数学条件判断[编辑 | 编辑源代码]
使用解析失败 (语法错误): {\displaystyle 公式} 计算:
Sass实现:
@function fluid-size($viewport) {
@if $viewport < 400px {
@return 16px;
} @else if $viewport > 1200px {
@return 24px;
} @else {
@return calc(4vw + 8px);
}
}
常见问题[编辑 | 编辑源代码]
- Q: 条件语句会增加CSS文件体积吗?
A: 不会,预处理器会在编译时评估条件,最终CSS只包含匹配的样式。
- Q: 能否在原生CSS中使用条件逻辑?
A: 原生CSS通过@supports
和CSS变量可以实现有限的条件判断,但远不如预处理器灵活。
最佳实践[编辑 | 编辑源代码]
1. 将复杂条件逻辑封装在mixin或function中
2. 使用有意义的变量名(如$is-dark-theme
而非$flag
)
3. 避免嵌套超过3层的条件判断
4. 配合@error
指令验证输入(Sass)
@mixin border-radius($value) {
@if type-of($value) != number {
@error "border-radius需要数字值,收到的是 #{type-of($value)}";
}
border-radius: $value;
}