CSS 预编译语言stylus+弹性布局的小例子-手风琴
前言
Stylus 是一种 CSS 预编译语言,它支持预编译,可以将 Stylus 代码转换为 CSS 代码。与传统的 CSS 相比,Stylus 提供了一些额外的功能和语法,使得 CSS 的编写更加简洁和高效。
html代码-很简单的页面没什么特殊的,重点在后面的stylus
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="./common.css" />
</head>
<body>
<ul class="accordion">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
</body>
</html>
上代码,后面解释
* /*这是一个通配符选择器,表示选择所有的元素。*/
margin 0 /*将所有元素的外边距都设置为 0*/
padding 0 /*将所有元素的内边距都设置为 0*/
box-sizing border-box/*设置盒模型为“边框盒模型”*/
ul,li
list-style none /*列表项不会显示默认的小圆点、数字等标记*/
.accordion
display flex /*元素以 Flex 弹性布局来显示*/
width 600px
height 200px
li
flex 1/*子元素平分空间*/
cursor pointer /*当鼠标移动到具有该属性的元素上时,它将变成一个手形图标*/
line-height 200
text-align center
color white
transition flex 500ms /*为元素的 `flex` 属性添加一个过渡效果,时长为 500 毫秒。看起来更自然*/
&:nth-child(1) /*选中父元素下的第一个子元素。特别注意&,&表示在在当前的父元素下的选择的第一个,如果没有就不会在意父元素是谁*/
background-color black
&:nth-child(2)
background-color red
&:nth-child(3)
background-color blue
&:nth-child(4)
background-color rgb(230, 15, 169)
&:nth-child(5)
background-color rgb(179, 255, 0)
&:nth-child(6)
background-color rgb(246, 255, 0)
&:hover /*它用于当鼠标悬停在元素上时应用特定的样式*/
flex 2
写的是 stylus 用的是编译后的 css 文件
在终端中执行,下面的命令
stylus common.styl -o common.css 将stylus文件编译成css文件
stylus common.styl -w common.css 监听,持续将stylus文件编译成css文件
用vscode软件中的stylus插件可以便捷生成,不用一个个字母敲
stylus
css 超集,支持预编译
省事{}: ; 都不需要了,取而代之的 tab 缩进
选择器也可以缩进
自动加上限定前缀
既缩进,又表示同一级别,& : checked :nth-child
模块性 stylus 给 css 给 css 引入编程特性
编译后的css文件
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
ul,
li {
list-style: none;
}
.accordion {
display: flex;
width: 600px;
height: 200px;
}
.accordion li {
flex: 1 /*子元素平分空间*/;
cursor: pointer;
line-height: 200;
text-align: center;
color: #fff;
transition: flex 500ms;
}
.accordion li:nth-child(1) {
background-color: #000;
}
.accordion li:nth-child(2) {
background-color: #f00;
}
.accordion li:nth-child(3) {
background-color: #00f;
}
.accordion li:nth-child(4) {
background-color: #e60fa9;
}
.accordion li:nth-child(5) {
background-color: #b3ff00;
}
.accordion li:nth-child(6) {
background-color: #f6ff00;
}
.accordion li:hover {
flex: 2;
}
小结
使用 Stylus 可以提高 CSS 的开发效率,减少代码的重复和复杂性。它在一些前端项目中被广泛应用,特别是在需要更高级的样式管理和代码组织的情况下。