Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make cross-browser CSS3 code DRY?

Tags:

javascript

css

When I want to create a gradient background in CSS3 I have to do this:

background-color: #3584ba;
background-image: -webkit-gradient(linear, left top, left bottom, from(#54a0ce), to(#3584ba)); /* Safari 4+, Chrome */
background-image: -webkit-linear-gradient(top, #54a0ce, #3584ba); /* Safari 5.1+, Chrome 10+ */
background-image:    -moz-linear-gradient(top, #54a0ce, #3584ba);  /* FF3.6 */
background-image:      -o-linear-gradient(top, #54a0ce, #3584ba); /* Opera 11.10+ */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#54a0ce', endColorstr='#3584ba'); /* IE */

and this is really annoying. Is there a better solution, for example a jQuery plugin, that will make my code cross browser compatible, if I just use:

background-image: -webkit-linear-gradient(top, #54a0ce, #3584ba); /* Safari 5.1+, Chrome 10+ */

for example? Is there a tool to help me write CSS3 code more easy?

like image 386
Tamás Pap Avatar asked Mar 10 '12 11:03

Tamás Pap


2 Answers

There are many tools for this:

  • http://lesscss.org/
  • http://leafo.net/lessphp/
  • http://sass-lang.com/
  • http://compass-style.org/

These are generally referred to as CSS Preprocessors.

You would end up writing something like this once, like a function definition (usually called a "mixin"):

.linear-gradient(@start, @end) {
    background-color: @end;
    background-image: -webkit-gradient(linear, left top, left bottom, from(@start), to(@end)); /* Safari 4+, Chrome */
    background-image: -webkit-linear-gradient(top, @start, @end); /* Safari 5.1+, Chrome 10+ */
    background-image:    -moz-linear-gradient(top, @start, @end);  /* FF3.6 */
    background-image:      -o-linear-gradient(top, @start, @end); /* Opera 11.10+ */
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='@start', endColorstr='@end'); /* IE */
}

Then to apply:

.my-class {
    .linear-gradient(#54a0ce, #3584ba);
}
.my-other-class {
    .linear-gradient(#ccc, #aaa);
}

Highly recommend.

like image 66
Wesley Murch Avatar answered Oct 12 '22 10:10

Wesley Murch


You could always use an online tool to generate them for you:

http://www.colorzilla.com/gradient-editor/

http://www.css3maker.com/css-gradient.html

like image 23
Marcelo Mason Avatar answered Oct 12 '22 09:10

Marcelo Mason