[英]CSS3 multiple backgrounds across selectors
What I want to achieve is to set background in two separate CSS classes (using CSS3's multiple backgrounds would be great).我想要实现的是在两个单独的 CSS 类中设置背景(使用 CSS3 的多个背景会很棒)。 I would like to that with as little markup as possible and to be universal.
我希望尽可能少的标记并且是通用的。
Example:例子:
CSS CSS
.button {
display: block;
}
.green {
background-color: #87b400;
background: -moz-linear-gradient(top, #a4d400, #739e00);
}
.icon {
background-repeat: no-repeat;
}
.icon.add {
background-image: url('../img/icons/add.png');
}
HTML HTML
<a href="#" class="button green icon add">add item</a>
<input type="submit" name="example" value="add item" class="button green icon add" />
<button type="submit" class="button green icon add">add item</button>
I realize that i can do something like that我意识到我可以做类似的事情
<a href="#" class="button green"><span class="icon add">add item</span></a>
but I think that there is a better way and I wouldn't be able to use it inside input
element.但我认为有更好的方法,我无法在
input
元素中使用它。
I also don't want to do something like this我也不想做这样的事情
.button.green.icon.add {
background: -moz-linear-gradient(top, #a4d400, #739e00),
url('../img/icons/add.png');
}
because having, let's say, 5 colors and 11 icons it is going to be a horror.因为拥有,比方说,5 种颜色和 11 个图标,这将是一种恐怖。
DaiYoukai is right, CSS3 multiple image backgrounds - can not be used across selectors. DaiYoukai 是对的,CSS3 多图像背景 - 不能跨选择器使用。
Workaround: you can use CSS3 Content feature - it virtually create additional element.解决方法:您可以使用 CSS3 内容功能 - 它实际上创建了额外的元素。
CSS CSS
.icon{
background-image: url('../img/icons/icon.png');
width:16px;
height:16px;
}
.icon.add:after {/* new virtual layer */
background-image: url('../img/icons/icon_add.png');
content: "";
display: block;
position: absolute;
width:16px;
height:16px;
}
Note: Modern browsers correctly supports both CSS3 features, except IE:注意:现代浏览器正确支持这两种 CSS3 特性,IE 除外:
It is my understanding that CSS3 multiple image backgrounds are only possible in the same declaration.我的理解是 CSS3 多图像背景只能在同一个声明中使用。
http://www.w3.org/TR/css3-background/#layering http://www.w3.org/TR/css3-background/#layering
If jQuery is an option:如果 jQuery 是一个选项:
$(".green, .icon.add").each(function () {
var backgrounds = [];
if ($(this).hasClass("green"))
backgrounds.push("linear-gradient(#a4d400, #739e00)");
if ($(this).hasClass("icon") && $(this).hasClass("add"))
backgrounds.push("url('../img/icons/add.png')");
$(this).css("background", backgrounds.join(", "));
});
The solution with :after
can have some unwanted side effects in some situations, and you can only have one of it.带有
:after
的解决方案在某些情况下可能会产生一些不需要的副作用,并且您只能拥有其中一种。 With this you can have an unlimited amount of backgrounds.有了这个,您可以拥有无限量的背景。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.