Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a generic way to add vendor prefixes in LESS?

Tags:

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; } 

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?

like image 487
BenMorel Avatar asked Sep 01 '13 12:09

BenMorel


People also ask

What is the vendor specific prefix for Safari and Chrome?

The most common browser CSS prefixes you will see in older code bases include: -webkit- (Chrome, Safari, newer versions of Opera and Edge, almost all iOS browsers including Firefox for iOS; basically, any WebKit or Chromium-based browser) -moz- (Firefox)


1 Answers

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.

See for example: less-plugin-autoprefix


Original answer:

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); } 

Output:

#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; } 

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); } 
like image 95
seven-phases-max Avatar answered Sep 20 '22 19:09

seven-phases-max