0%

Generate Css Utils by Less

Less as a pre-compile processor, is often used in our project.Mostly only small part is been taken advance of by us. Therefor I decide to have a deep exploit over it.

Css utils is very common either when you are in your project or you are building a library. A majority of us must tried boot-css before. There are a lot of utilized css class-name. For instance: text-center,font-sm .

Recently I was coping with a project which has same demand.I have a common.css where put all the css utils in.All of the style is code by manually. I wish we can be more efficient. Then less is back to my eyes again.

Usually we use the nesting feature,that’s really useful for us and saved a lot time for us of looking up the parent.

1
2
3
4
5
6
.content {
color: red;
.list {
border-color: blue;
}
}

That’s pretty easy and easy to master. when it refers to some advanced feature,it get a little tricky.
For me , I prefer use another two feature: variable and namespace.

1
2
3
4
5
6
7
@ns: ex-css;
.@{ns}-name{
text-align: center;
&-title{
font-size: 1.8rem;
}
}

whereas for create utils , these features are not enough. But Less offered us rich functions that can fulfill any requirements of us.

variable variable: I like this feature, it make every variable are flexible, you can define any variable and make up to new variable.

1
2
3
4
5
6
7
8
9
10
@primary: green;
@secondary: blue;

.section {
@color: primary;

.element {
color: @@color;
}
}

so now, I will take full use of it for generate my css utils.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@position:top,right,bottom,left;
@size: xs,sm,md,lg;
@margin-left:ml;@margin-right:mr;@margin-top:mt;@margin-bottom:mb;
@sm: 1em; @xs: .5em;@md:1.5em;@lg:2em;
.gen(@OldValue){
each(@size,{
@mg: e("margin-@{OldValue}");// mg = margin-left
@mgDir: @@mg; // variable variables
@mg-class: e("@{mgDir}-@{value}");//mg-class=ml-sm e: transform 'ml-sm' to ml-sm
@pd: "padding-@{OldValue}"; // you have to use string to collocate variable
@pd-class: "@{pd}-@{value}";
.@{mg-class} {
@{mg}: @@value;
}
})
}

each(@position,{
.gen(@value)
})

Here is a note for me, I wish I can use it more smoothly at next time.