使用LESS 或SASS 之类的东西,这很容易合法地做到。像这样创建一个 mixin(健壮的版本):
.auto-gradient(@color) {
/* Use any of the built in functions like saturate() or spin() */
@topcolor: lighten(@color, 20);
@bottomcolor: darken(@color, 20);
background: @color;
background: -webkit-gradient(linear, 0 0, 0 bottom, from(@topcolor), to(@bottomcolor));
background: -webkit-linear-gradient(@topcolor, @bottomcolor);
background: -moz-linear-gradient(@topcolor, @bottomcolor);
background: -ms-linear-gradient(@topcolor, @bottomcolor);
background: -o-linear-gradient(@topcolor, @bottomcolor);
background: linear-gradient(@topcolor, @bottomcolor);
/* If using PIE.htc for IE */
-pie-background: linear-gradient(@topcolor, @bottomcolor);
behavior: url(pie.htc);
}
用法:
.my-button {
.auto-gradient(darkviolet);
}
这将编译为有效的 CSS(3),它应该是这样的:
.my-button {
background:darkviolet;
background:-webkit-gradient(linear,0 0,0 bottom,from(#c43aff),to(#4c006d));
background:-webkit-linear-gradient(#c43aff,#4c006d);
background:-moz-linear-gradient(#c43aff,#4c006d);
background:-ms-linear-gradient(#c43aff,#4c006d);
background:-o-linear-gradient(#c43aff,#4c006d);
background:linear-gradient(#c43aff,#4c006d);
}
注意:我自己使用 lessphp,而我现在使用的版本似乎会阻塞命名颜色,例如 DarkViolet 被传递给 lighten/darken,除非它们是小写的。