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

1. 嵌套选择器

css 复制代码
#content {
  article {
    h1 { color: #333 }
    p { margin-bottom: 1.4em }
  }
  aside { background-color: #EEE }
}

编译后

css 复制代码
#content article h1 { color: #333 }
#content article p { margin-bottom: 1.4em }
#content aside { background-color: #EEE }

2. 变量声明和使用

css 复制代码
$width: 100px;
$height: 100px;
$bg-red: #ff4040;
.box{
    width: $width;
    height: $height;
    background: $bg-red;
}

编译后

css 复制代码
.box{
  width: 100px;
  height: 100px;
  background: #ff4040;
}

3. 父选择器标识符&

css 复制代码
article a {
  color: blue;
  &:hover { color: red }
}

编译后

css 复制代码
article a { color: blue }
article a:hover { color: red }

4. 嵌套属性

css 复制代码
nav {
  border: {
    style: solid;
    width: 1px;
    color: #000;
  }
}

编译后

css 复制代码
nav {
  border-style: solid;
  border-width: 1px;
  border-color: #ccc;
}

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

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

编译后

css 复制代码
.box1{
  background: cyan;
  width: 100px;
  height: 100px;
}
.box2{
  background: #ff4040;
  width: 100px;
  height: 100px;
}

6. 给混合器传参

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

编译后

css 复制代码
a { color: blue; }
a:hover { color: red; }
a:visited { color: green; }

7. @for

用法1:through

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

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

编译后

css 复制代码
.w-100 {
  width: 100px;}
.w-200 {
  width: 200px;}
.w-300 {
  width: 300px;}

用法2:to

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

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

编译后

css 复制代码
.w-100 {
  width: 100px;}
.w-200 {
  width: 200px;}
相关推荐
人工智能训练师3 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny073 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy4 小时前
css的基本知识
前端·css
昔人'4 小时前
css `lh`单位
前端·css
Nan_Shu_6145 小时前
Web前端面试题(2)
前端
知识分享小能手5 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
2501_918126916 小时前
用html5写一个flappybird游戏
css·游戏·html5
蚂蚁RichLab前端团队6 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光7 小时前
css之一个元素可以同时应用多个动画效果
前端·css
huangql5207 小时前
npm 发布流程——从创建组件到发布到 npm 仓库
前端·npm·node.js