我希望能够在网页中动态创建任何颜色的漂亮按钮,而无需提前为每种颜色定义单独的 CSS 类。
使用带有 Alpha channel 的 CSS3 渐变似乎是实现此目的的最佳方法,将低不透明度渐变叠加在纯色背景色之上。
但是,我对 CSS 的了解还不够,甚至无法判断这是否可行,更不用说实际实现它了。
我在网上找到了一些看起来会有帮助的资源:
有更多 CSS 经验的人可以告诉我这是否可行,也许可以向我指出其他资源,以便更容易实现这一点?
最佳答案
使用类似 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
等命名颜色被传递到变亮/变暗感到窒息,除非它们是小写的。
关于button - 任意颜色渐变按钮的通用 CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11586309/