15

我知道可以使用 CSS 制作多个背景图层,但我可以对来自不同类的多个背景进行分层吗?假设我有 div 作为瓷砖,可以有山脉或丘陵,并且可以属于某个国家。

.mountain {
    background: url("mountain.png");
}
.hill {
    background: url("hill.png");
}
.bluecountry {
    background: url("bluecountry.png");
}
.redcountry {
    background: url("redcountry.png");
}
.greencountry {
    background: url("greencountry.png");
}

将是我的CSS。但是,这不起作用;当我做类似的事情时

<div class="hill bluecountry">

它不会对背景进行分层,只会使用其中一个。有什么办法可以使这项工作?我实际上有比这更多的东西,并且必须为每种可能的组合单独编写 CSS 多个背景将是巨大的浪费时间。

4

2 回答 2

3

无法background使用多个类合并属性——它只能设置一次。你可以做的是:

  1. 创建一个容器 div ( position: relative)
  2. 在容器内放置多个 div ( position: absolute)
  3. 对每个子 div 应用一个单独的类
  4. 每个图像都可以使用top: 0px; left: 0px;, 和 with定位在容器内background-position

这是我的意思的一个例子:

HTML

<div class="container">
    <div class="first"></div>
    <div class="second"></div>
</div>​

CSS

html, body { height: 100%; }
div { 
    display: inline-block;
    width: 400px; 
    height: 100px; 
}
.container {
    position: relative;
}
.first, .second {
    position: absolute;
    left: 0;
    top: 0;
}
.first { 
    background: url(http://lorempixel.com/200/100/sports/1) no-repeat; 
}
.second { 
    background: url(http://lorempixel.com/200/100/sports/2) no-repeat; 
    background-position: right center;
}

http://jsfiddle.net/32G4A/2

于 2012-12-02T01:51:55.607 回答
0

如果 jQuery 是一个选项:

$(".mountain, .hill, .bluecountry").each(function () {
  var backgrounds = [];
  if ($(this).hasClass("mountain"))
    backgrounds.push("url('mountain.png')");
  if ($(this).hasClass("hill"))
    backgrounds.push("url('hill.png')");
  if ($(this).hasClass("bluecountry"))
    backgrounds.push("url('bluecountry.png')");
  $(this).css("background", backgrounds.join(", "));
});
于 2020-10-04T22:44:46.357 回答