开发者

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). I would like to that with as little markup as possible and to be universal.

Example:

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>

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.

I also don't want to do something like this开发者_StackOverflow

.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.


DaiYoukai is right, CSS3 multiple image backgrounds - can not be used across selectors.

Workaround: you can use CSS3 Content feature - it virtually create additional element.

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 multiple backgrounds - from IE9.
  • CSS3 Content - from IE8.


It is my understanding that CSS3 multiple image backgrounds are only possible in the same declaration.

http://www.w3.org/TR/css3-background/#layering


If jQuery is an option:

$(".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. With this you can have an unlimited amount of backgrounds.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜