预编译sass的出现,css也可以变得优雅

本文详细介绍了CSS编译过程中的几个关键概念,包括嵌套规则的简化、变量和混合器的使用、父选择器标识符的处理以及@for循环的不同用法,展示了CSS代码在编译后的简洁性。
摘要由CSDN通过智能技术生成

1. 嵌套选择器

#content {
  article {
    h1 { color: #333 }
    p { margin-bottom: 1.4em }
  }
  aside { background-color: #EEE }
}

编译后

#content article h1 { color: #333 }
#content article p { margin-bottom: 1.4em }
#content aside { background-color: #EEE }

2. 变量声明和使用

$width: 100px;
$height: 100px;
$bg-red: #ff4040;
.box{
    width: $width;
    height: $height;
    background: $bg-red;
}

编译后

.box{
  width: 100px;
  height: 100px;
  background: #ff4040;
}

3. 父选择器标识符&

article a {
  color: blue;
  &:hover { color: red }
}

编译后

article a { color: blue }
article a:hover { color: red }

4. 嵌套属性

nav {
  border: {
    style: solid;
    width: 1px;
    color: #000;
  }
}

编译后

nav {
  border-style: solid;
  border-width: 1px;
  border-color: #ccc;
}

5. 混合器(整合重复代码)

  • @mixin 定义混合器
  • @include 使用混合器
  1. 定义混合器
@mixin box-style {
  width: 100px;
  height: 100px;
}
  1. 使用混合器
.box1{
  background: cyan;
  @include box-style;
}
.box2{
  background: #ff4040;
  @include box-style;
}

编译后

.box1{
  background: cyan;
  width: 100px;
  height: 100px;
}
.box2{
  background: #ff4040;
  width: 100px;
  height: 100px;
}

6. 给混合器传参

  • @mixin接收参数使用 @include传参,这种方式跟JavaScript的function很像
  1. 定义混合器
@mixin link-colors($normal, $hover, $visited) {
  color: $normal;
  &:hover { color: $hover; }
  &:visited { color: $visited; }
}
  1. 使用混合器并传参进去
a {
  @include link-colors(blue, red, green);
}

编译后

a { color: blue; }
a:hover { color: red; }
a:visited { color: green; }

7. @for

用法1:through

条件范围包含 start 与 end 的值 @for $var from <start> through <end>

@for $i from 1 through 3 {
  .w-#{$i * 100} { width: 100px * $i; }
}

编译后

.w-100 {
  width: 100px;}
.w-200 {
  width: 200px;}
.w-300 {
  width: 300px;}

用法2:to

条件范围只包含 start 的值不包含 end 的值 @for $var from <start> to <end>

@for $i from 1 to 3 {
  .w-#{$i * 100} { width: 100px * $i; }
}

编译后

.w-100 {
  width: 100px;}
.w-200 {
  width: 200px;}
  • 14
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

来一颗砂糖橘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值