Wednesday, 15 May 2013

less - How to write reusable classes in css -



less - How to write reusable classes in css -

this isn't question of such, rather want know rather understanding on reusable class in css correct. in example, have 2 divs. , want add together padding-left both, different values. (e.g. div 1 has padding left of 10px, , div2 , padding left of 15px). want write reusable css classes, help of less function.

example1

<div id="div1" class="small-left-space"> </div> <div id="div2" class="large-left-space"> </div>

//css , less

.padleft(@value) { padding-left: @value; } .small-left-space{ .padleft(10px); } .large-left-space{ .padleft(100px); }

example 2

html

<div id="box1" class="bigbox redbackground smallleftspace "></div> <div id="box2" class="mediumbox bluebackground mediumleftspace"></div> <div id="box3" class="smallbox greenbackground largeleftspace"></div>

css/less

.bigbox { width: 500px; height:500px; } .mediumbox{ width:300px height:300px; } .smallbox{ width:100px height:100px; } .redbackground{ .backgroundcolor(red); } .bluebackground{ .backgroundcolor(blue); } .greenbackground{ .backgroundcolor(green); } .smallleftspace{ margin-left: 20px; } .mediumleftspace{ margin-left: 50px; } .largeleftspace{ margin-left: 100px; } .backgroundcolor(@value){ background-color: @value; }

as you're using less, best thing utilize reusable mixins instead of reusable classes. has several advantages :

if mixin not used, it's not compiled , doesn't appears in generated css your html markup clean, semantic, without many cosmetic classes you can utilize 1 mixin (with parameter) have used several css classes

this way create awesome, clean , reusable code.

example:

less file, mixins:

/* size */ .box(@value) { width: @value; height: @value; } .bigbox() { .box(500px); } .mediumbox() { .box(300px); } .smallbox() { .box(100px); } /* background-color */ .backgroundcolor(@value){ background-color: @value; } /* margin-left */ .leftspace(@value) { margin-left: @value; } .smallleftspace() { .leftspace(20px); } .mediumleftspace() { .leftspace(50px); } .largeleftspace() { .leftspace(100px); } #box2 { .mediumbox(); .backgroundcolor(blue); .mediumleftspace(); } #box3 { .smallbox(); .backgroundcolor(green); .largeleftspace(); }

css file, generated:

#box2 { width: 300px; height: 300px; background-color: #0000ff; margin-left: 50px; } #box3 { width: 100px; height: 100px; background-color: #008000; margin-left: 100px; }

html markup used, without cosmetic classes:

<div id="box2"></div> <div id="box3"></div>

css less

No comments:

Post a Comment