有没有一种通用的方法可以在LESS中添加供应商前缀? [英] Is there a generic way to add vendor prefixes in LESS?
问题描述
我目前有一个mixins.less
文件,几乎所有的mixin基本上都是相同的:
I currently have a mixins.less
file, where almost all mixins are basically the same:
.border-radius(@radius) {
-webkit-border-radius: @radius;
-khtml-border-radius: @radius;
-moz-border-radius: @radius;
border-radius: @radius;
}
.box-shadow(@value) {
-webkit-box-shadow: @value;
-khtml-box-shadow: @value;
-moz-box-shadow: @value;
box-shadow: @value;
}
有没有办法创建某种通用的mixin,我可以这样称呼:
Is there a way to create some kind of generic mixin, that I could call like this:
.vendor('border-radius', '3px');
.vendor('box-shadox', '10px 10px');
哪个会产生与上述相同的结果?
and which would produce the same result as above?
推荐答案
注意:
建议停止使用此技术,并考虑使用专用的前缀工具(例如 Autoprefixer , -无前缀等).如今,通过CSS预处理器mixin(Less,SCSS或其他任何东西)对供应商前缀进行硬编码是一种纯粹的反模式,并且被认为是有害的.自动前缀工具将使您的代码干净,易读,面向未来,并易于维护/自定义.
Notice:
The recommendation is to stop rely on this technique and consider using a dedicated prefixing tool (e.g. Autoprefixer, -prefix-free etc.). Hardcoding vendor prefixes via CSS pre-processor mixins (Less, SCSS or whatever) is a pure anti-pattern these days and considered harmful. Auto-prefixing tools will make your code clean, readable, future-proof and easily maintainable/customizable.
例如参见: less-plugin-autoprefix
See for example: less-plugin-autoprefix
好吧,当前LESS不支持属性名称插值",因此您不能在属性名称中使用变量.但是,有一个黑客:如何在less中将属性名称作为参数传递给mixin 因此,如果您不介意输出CSS中的虚拟"属性,那么我们开始:
Well, currently LESS does not support "property name interpolation" so you cannot use a variable in property names. There's a hack however: How to pass a property name as an argument to a mixin in less So if you don't mind "dummy" properties in the output CSS, here we go:
.property_(@property, @value) {
_: ~"; @{property}:" @value;
}
.vendor(@property, @value) {
.property_('-webkit-@{property}', @value);
.property_( '-khtml-@{property}', @value);
.property_( '-moz-@{property}', @value);
.property_( @property, @value);
}
#usage {
.vendor(border-radius, 3px);
.vendor(box-shadow, 10px 10px);
}
输出:
#usage {
_: ; -webkit-border-radius: 3px;
_: ; -khtml-border-radius: 3px;
_: ; -moz-border-radius: 3px;
_: ; border-radius: 3px;
_: ; -webkit-box-shadow: 10px 10px;
_: ; -khtml-box-shadow: 10px 10px;
_: ; -moz-box-shadow: 10px 10px;
_: ; box-shadow: 10px 10px;
}
更新:
Less v1.6.0引入了属性插值功能,因此您现在不需要不再有任何骇客了:
Update:
Less v1.6.0 introduced Property Interpolation feature so now you don't need any hacks anymore:
.vendor(@property, @value) {
-webkit-@{property}: @value;
-khtml-@{property}: @value;
-moz-@{property}: @value;
@{property}: @value;
}
#usage {
.vendor(border-radius, 3px);
.vendor(box-shadow, 10px 10px);
}
这篇关于有没有一种通用的方法可以在LESS中添加供应商前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!