首页 > 解决方案 > 将 2 个背景图像应用到来自不同 CSS 类的一个 HTML 元素

问题描述

我将 2 个 CSS 类应用于div 在线示例

<div class="img1 img2">
</div>

使用 LESS,我尝试将 2 个背景图像应用于div每个类中的一个:

div {
  
  border: 1px solid red;
  height: 200px;
  
  &.img1 {
    background+: url('https://via.placeholder.com/100/09f/fff') no-repeat left top;
  } // img1
  
  &.img2 {
    background+: url('https://via.placeholder.com/100/09f/fff') no-repeat right bottom;
  } // img2
  
}

但只应用了第二个背景。

Less的合并功能不就是为了这个吗?

标签: htmlcssless

解决方案


这是一种将多个背景包含到单个元素中的方法: https ://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds

.multi-bg-example {
  width: 100px;
  height: 400px;
  background-image: url('https://via.placeholder.com/100/09f/fff'),
          url('https://via.placeholder.com/100/09f/fff');
  background-repeat: no-repeat,
          no-repeat;
  background-position: bottom left,
          top right;
 }
<div class="multi-bg-example" />

所以你一个一个设置道具,它们适用于相应的背景。


推荐阅读