【发布时间】:2017-06-01 08:33:20
【问题描述】:
我正在努力在一个大型框架上实现 RTL 支持。为此,我用 mixins 替换了所有方向性的规则,例如:
a {
@include padding(0, 1px, 0, 0);
@include margin(0, 1px, 0, 0);
}
这样做是根据文档的方向添加相关的填充/边距。
每个 mixin 都会为 ltr 和 rtl 创建一个 case。
这是这些 mixin 的结果:
[dir="ltr"] a {
padding: 0 1px 0 0;
}
[dir="rtl"] a {
padding: 0 0 0 1px;
}
[dir="ltr"] a {
margin: 0 1px 0 0;
}
[dir="rtl"] a {
margin: 0 0 0 1px;
}
这很好用,但是会创建很多重复的选择器(每个 mixin 2 个),因此 css 包的大小增加了 100kb(20%),其中很大一部分是因为这种重复。
预期结果:
[dir="ltr"] a {
padding: 0 1px 0 0;
margin: 0 1px 0 0;
}
[dir="rtl"] a {
padding: 0 0 0 1px;
margin: 0 0 0 1px;
}
在不影响 css 执行顺序的情况下,我可以做哪些后处理来合并相关的重复选择器?
不受欢迎的情况:
假设我有这个代码:
b.s1 {
padding-left: 1px;
margin: 0;
}
b.s2 {
padding-left: 0;
margin: 1px;
}
b.s1 {
padding-left: 1px;
}
如果我向上合并 b.s1,那么 s2 的 padding-left 可以覆盖它。 如果我向下合并 b.s1,则覆盖 s2 的边距。
有没有办法解决这个问题?
编辑:原始代码
// Add property for all sides
// @param {string} $prop
// @param {string} $top
// @param {string} $end
// @param {string} $bottom
// @param {string} $start
// @param {boolean} $content include content or use default
// ----------------------------------------------------------
@mixin property($prop, $top, $end: $top, $bottom: $top, $start: $end, $content: false) {
@if $top == $end and $top == $bottom and $top == $start {
@include multi-dir() {
#{$prop}: $top;
}
} @else if $top == $bottom and $end == $start and $top != null and $end != null {
@include multi-dir() {
#{$prop}: $top $end;
}
} @else if $end == $start and $top != null and $end != null and $bottom != null {
@include multi-dir() {
#{$prop}: $top $end $bottom;
}
} @else if $top != null and $end != null and $bottom != null and $start != null {
@include ltr() {
#{$prop}: $top $end $bottom $start;
}
@include rtl() {
#{$prop}: $top $start $bottom $end;
}
} @else {
@if $content == true { // TODO check if @content exists instead
@content;
} @else {
@include property-horizontal($prop, $start, $end);
@include multi-dir() {
#{$prop}-top: $top;
#{$prop}-bottom: $bottom;
}
}
}
}
// Add padding for all sides
// @param {string} $top
// @param {string} $end
// @param {string} $bottom
// @param {string} $start
// ----------------------------------------------------------
@mixin padding($top, $end: $top, $bottom: $top, $start: $end) {
@include property(padding, $top, $end, $bottom, $start);
}
// Add margin for all sides
// @param {string} $top
// @param {string} $end
// @param {string} $bottom
// @param {string} $start
// ----------------------------------------------------------
@mixin margin($top, $end: $top, $bottom: $top, $start: $end) {
@include property(margin, $top, $end, $bottom, $start);
}
【问题讨论】:
-
你也可以发布你的mixin代码吗?为什么不能将 padding 和 margin 结合到一个 mixin 中并通过传递正确的参数来选择合适的呢?
-
看起来好像您正在使用预处理器;请edit您的问题并包含该预处理器的标签。
-
@MikeMcCaughan 我正在使用经过 gulp 预处理的标准 sass。我在答案中添加了一个 gulp 任务,它以有限的方式完成了我需要的任务