CSS嵌套模块(Nesting Module)
前言
原始 css 比较质朴,出来了很多方言,如 scss 等。css 的官方标准组织终于干活了,然后就有了 css nesting module 标准。
不过这个标准还没有正式,所以现在通过 postcss 工具来模拟实现它。具体而言就是 postcss-nesting 插件。
语法
嵌套
a.b c .d {color:red;}
a.b c e {color:blue;}
/* 改进 */
a.b c{
.d {color:red;}
& e {color:blue;}
}
- & :外层元素占位符,例:a.b c,即用 a.b c 替换掉 &
- 后代是默认关系(但语法上要求有些情况需要使用 & 符号占位)
- 非标识符开头可以省略 &,如 .d 可以,e 不可以
- & 发挥占位符的作用,不一定是放在开始位置,也不一定只能用一次
- 嵌套规则组成(类似二元关系 a + b)
- 组合器:
- 默认:后代
-
>
:大郎
- ~:弟弟们
- +:相邻
- 外层选择器:外层 a.b c
- 嵌套选择器:内层 .d 或 e
- css 选择器类型
- *:所有东西
- a:标签
- .a:class 属性指定的名称
- #a:id 属性指定的名称
-
[a]
: 具有 a 属性
-
[a="xx"]
:具有 a 属性且值为 xx 时
- a:visited :伪类(动态信息)
- p::first-line :伪元素(概念元素)
- a.a: a 标签,且类 .a(交集)
- a,.a: a 标签,或类 .a(并集)
At 规则
- @media:媒体条件
- @supports:指定条件
- @layer:级联层
- @scope:
- @page:打印规则
- @container
- @charset:字符编码
a {
color:red;
@media (orientation: landscape) {
color:blue;
}
}
/* 相当 */
a {
color:color
@media (orientation: landscape) {
& {
color:blue;
}
}
}
伪类和伪元素
处于某种状态下才有效的伪类,也可以视为条件语句。格式 :xxx
由 css 动态添加的元素(具有 content 内容属性),称为伪元素。格式 ::xxx
规则: & 无法替代伪类和伪元素。
状态:
- :link:未访问链接
- :visited:已访问链接
- :hover:指针悬停之上
- :active:激活链接
- :any-link:可链接元素
- :local-link:本地链接
- :target:当前标题
- :focus:获得焦点
- :focus-within:子元素获得焦点时
- :focus-visible:焦点框
- :checked:选中
- :default:默认元素
- :defined:已定义
- :indeterminate:未赋值
- :disabled:禁用
- :enabled:启用
- :valid:验证
- :out-of-range:数值超范围
- :in-range:范围内
- :fullscreen:全屏
- :modal:模态对话框
属性:
- :placeholder-shown:占位提示符
- :required:必填
- :optional:可选
- :lang():语言
- :autofill:内容为自动填充
逻辑元素:
- :root:根元素
- :first:打印的首页
- :first-child:兄弟元素中的第一项
- :first-of-type:同类元素中的第一个
- :last-child:逆序版
- :last-of-type:逆序版
- :only-child:孤儿
- :only-of-type:孤类
- :empty:无子元素
- :nth-child:第 x 个元素。参数 1n+3 => 1 * n + 3,n 从 0 开始递增,下标从 1 开始
- :nth-of-type:同类元素第 x 个。
- :nth-last-child:逆序版
- :nth-last-of-type:逆序版
函数:
- :is():集合(元素最高优先级,容错)
- :not():不在集合中的其他元素(不容错)
- :where():集合(优先级 0,容错)
- :has():具备某种组合关系
伪元素:
- ::after:在元素后添加
- ::before:前
- ::backdrop:全屏时渲染
- ::cue:字幕
- ::file-selector-button:打开文件选择对话框按钮
- ::first-letter:首字母
- ::first-line:首行
- ::marker:小标签(如列表前的符号)
- ::selection:选中的文字
参考
- css nesting module 标准:https://www.w3.org/TR/css-nesting-1/