在CSS中将一个背景图像置于另一个中心

时间:2018-02-08 11:50:17

标签: javascript html css css3 less

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

Expected Image 但我得到了这样的形象。 Real Image

我的代码如下:

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;
  }
}

3 个答案:

答案 0 :(得分:2)

你需要更正你的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(仅一次,它会影响两个图像)

答案 1 :(得分:1)

第二个背景重复,因此请更改此属性:

background-repeat: no-repeat,repeat;

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

(并调整大小和/或位置)

答案 2 :(得分:0)

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

应更新如下。

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