您现在的位置是:网站首页 > 条件语句与循环文章详情
条件语句与循环
陈川
【
CSS
】
36744人已围观
3252字
条件语句与循环
CSS中的条件语句与循环虽然不如JavaScript那样灵活,但借助预处理器如Sass、Less等工具,可以实现动态样式逻辑。这些特性让样式表更具可维护性和扩展性。
CSS原生条件逻辑
CSS本身通过媒体查询(@media
)和特性查询(@supports
)实现基础条件判断:
/* 媒体查询示例 */
@media (max-width: 600px) {
.container {
padding: 10px;
}
}
/* 特性查询示例 */
@supports (display: grid) {
.grid-layout {
display: grid;
}
}
自定义属性(CSS变量)结合calc()
也能实现简单条件:
:root {
--primary-color: #3498db;
--secondary-color: #e74c3c;
}
.button {
background-color: var(--is-primary, var(--primary-color));
}
.button.secondary {
--is-primary: var(--secondary-color);
}
Sass中的条件控制
Sass提供@if
、@else if
、@else
等完整条件语句:
$theme: dark;
body {
@if $theme == light {
background: white;
color: #333;
} @else if $theme == dark {
background: #222;
color: #eee;
} @else {
background: #f9f9f9;
}
}
Less中的条件混合
Less通过带条件的混合(Mixin)实现逻辑判断:
.mixin(@color) when (lightness(@color) > 50%) {
background-color: black;
}
.mixin(@color) when (lightness(@color) <= 50%) {
background-color: white;
}
.box {
.mixin(#ddd); // 触发黑色背景
}
循环结构实现
Sass支持@for
、@each
和@while
三种循环:
/* @for 循环 */
@for $i from 1 through 5 {
.col-#{$i} {
width: 20% * $i;
}
}
/* @each 循环 */
$icons: success error warning;
@each $icon in $icons {
.icon-#{$icon} {
background-image: url('/icons/#{$icon}.png');
}
}
/* @while 循环 */
$counter: 3;
@while $counter > 0 {
.item-#{$counter} {
z-index: $counter;
}
$counter: $counter - 1;
}
实战应用案例
创建响应式间距工具类:
$spacing-sizes: (0, 4, 8, 16, 24, 32);
$spacing-directions: (
'': 'all',
't': 'top',
'r': 'right',
'b': 'bottom',
'l': 'left',
'x': 'horizontal',
'y': 'vertical'
);
@each $size in $spacing-sizes {
@each $prefix, $direction in $spacing-directions {
.p#{$prefix}-#{$size} {
@if $direction == 'all' {
padding: #{$size}px;
} @else if $direction == 'horizontal' {
padding-left: #{$size}px;
padding-right: #{$size}px;
} @else if $direction == 'vertical' {
padding-top: #{$size}px;
padding-bottom: #{$size}px;
} @else {
padding-#{$direction}: #{$size}px;
}
}
}
}
动态主题切换
结合CSS变量和条件逻辑实现主题系统:
$themes: (
light: (
bg: #ffffff,
text: #333333,
primary: #3498db
),
dark: (
bg: #222222,
text: #eeeeee,
primary: #1abc9c
)
);
@mixin theme-styles($theme) {
$colors: map-get($themes, $theme);
body[data-theme="#{$theme}"] {
--bg-color: #{map-get($colors, bg)};
--text-color: #{map-get($colors, text)};
--primary-color: #{map-get($colors, primary)};
}
}
@each $theme-name, $theme-colors in $themes {
@include theme-styles($theme-name);
}
性能优化建议
- 避免深层嵌套的条件判断
- 循环生成的类名数量需合理控制
- 预处理器的循环在编译时展开,不影响运行时性能
- 合并相似的条件分支减少输出代码量
// 不推荐
@for $i from 1 through 100 {
.width-#{$i} {
width: #{$i}px;
}
}
// 推荐
$useful-widths: 10, 20, 25, 33, 50, 75, 100;
@each $width in $useful-widths {
.w-#{$width} {
width: percentage($width / 100);
}
}
浏览器兼容方案
对于不支持CSS变量的旧浏览器,可以结合条件语句提供降级方案:
.element {
color: #333; // 旧浏览器回退值
@supports (--css: variables) {
color: var(--text-color, #333);
}
}