在 CSS 中将一张背景图片置于另一张图片的中央

Center one background image over the other in CSS

我有 2 张背景图片,我想将 image1 放置在 image2 上,使第一个以第二个为中心。 (图 1 是警告符号,图 2 是蓝色背景)。最终结果应如下图所示。

但我的形象是这样的。

我的代码如下:

CSS

.imgPin {
  background-repeat: no-repeat,repeat;
  bottom: -1px;
  left: -1px;
  height: 39px;
  width: 31px;
  background-size: 100% 100%;
  display: none;
  position: absolute;
  cursor: pointer;
  opacity: 0.75;
  z-index: 11;
  &.active {
    opacity: 1.0;
    z-index: 12;
  }
}

JavaScript

 var divElem = document.createElement("div");
 divElem .setAttribute( 'style', 'background: url( "caution.png" ), url("background.png")' );
 divElem .className = "imgPin";

有没有办法设置背景大小或以这种方式重复可以实现?任何帮助都是无价的。

谢谢!

更新:

我的最终 css 看起来像这样及其工作:

.imgPin{
  background-repeat: no-repeat;
  background-position:60% 30%,center;
  bottom: -1px;
  left: -1px;
  height: 39px;
  width: 31px;
  background-size:auto,100% 100%;
  display: none;
  position: absolute;
  cursor: pointer;
  opacity: 0.75;
  z-index: 11;
  &.active {
    opacity: 1.0;
    z-index: 12;
  }
}

第二个背景重复,所以改变这个属性:

background-repeat: no-repeat,repeat;

background-repeat: no-repeat,no-repeat;

(并微调大小and/or位置)

您的第二张背景图片重复 属性。

更新如下

background-repeat: no-repeat, no-repeat;

您需要更正您的 JS,您指定的 background 将覆盖 CSS 中指定的所有背景属性。因此,改为使用 background-image 来保留 CSS 属性:

var divElem = document.createElement("div");
 divElem .setAttribute( 'style', 'background-image: url( "caution.png" ), url("background.png")' );
 divElem .className = "imgPin";

如果仍然存在对齐问题,您可能需要调整 CSS:

  • 使用 background-size:coverbackground-size:contain 来避免图标拉伸,或者干脆不指定任何大小以保留原始图标。
  • 添加 background-position:center 以使两个图标居中。您还可以指定值以控制这样的位置 background-position: 5px 10px,10px 5px(也适用于 % 值)。
  • 然后指定background-repeat:no-repeat(只有一次,它会影响两个图像)