[英]CSS3 multiple backgrounds across selectors
我想要实现的是在两个单独的 CSS 类中设置背景(使用 CSS3 的多个背景会很棒)。 我希望尽可能少的标记并且是通用的。
例子:
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
<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>
我意识到我可以做类似的事情
<a href="#" class="button green"><span class="icon add">add item</span></a>
但我认为有更好的方法,我无法在input
元素中使用它。
我也不想做这样的事情
.button.green.icon.add {
background: -moz-linear-gradient(top, #a4d400, #739e00),
url('../img/icons/add.png');
}
因为拥有,比方说,5 种颜色和 11 个图标,这将是一种恐怖。
DaiYoukai 是对的,CSS3 多图像背景 - 不能跨选择器使用。
解决方法:您可以使用 CSS3 内容功能 - 它实际上创建了额外的元素。
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;
}
注意:现代浏览器正确支持这两种 CSS3 特性,IE 除外:
我的理解是 CSS3 多图像背景只能在同一个声明中使用。
如果 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(", "));
});
带有:after
的解决方案在某些情况下可能会产生一些不需要的副作用,并且您只能拥有其中一种。 有了这个,您可以拥有无限量的背景。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.