在 div 中对齐背景中的 2 个图像

Align 2 images in background in a div

我想在 div.

中放置 2 张图片作为背景图片

这是我输入的代码,但我只看到第二张图片。

#wrap-header {
  max-width: 100%;
  height: 400px;
  background-image: url("../assets/header_background.png"), url("../assets/circle_header_background.png");
  background-repeat: no-repeat;
  background-position: center bottom, center top;
}
<div id="wrap-header">

</div>

我想检索一张图片在另一张图片下的效果,或者一张图片作为第一层,第二层在底部。

我找不到办法。你能帮帮我吗?

您可以使用 CSS 选择器 :after:before

首先,将以下内容添加到#wrap-header:

#wrap-header {
    position: relative;
    overflow: hidden;
    max-width: 100%;
    height: 400px;
}

然后使用选择器:

#wrap-header:before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    height: 50%;
    width: 100%;
    background-image: url('image1');
    background-repeat: no-repeat;
    background-position: center
}

#wrap-header:after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    height: 50%;
    width: 100%;
    background-image: url('image2');
    background-repeat: no-repeat;
    background-position: center;
}

这可以借助伪元素 :before 和 :after

#wrap-header {
  max-width: 100%;
  height: 400px;
}

#wrap-header:before {
  content: "";
  width: 100%;
  height: 100%;
  background-image: url("https://boutiqueme.com/static/4/generated/30-pattern-44-ff81c0.png");
  background-repeat: no-repeat;
  background-size: cover;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
}

#wrap-header:after {
  content: "";
  width: 100%;
  height: 100%;
  background-image: url("https://cdn.pixabay.com/photo/2016/04/12/00/04/hero-1323464_960_720.png");
  background-repeat: no-repeat;
  background-size: cover;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}
<div id="wrap-header">

</div>

您可以使用 :before:after pseudo 选择器来实现此目的

/* Set #wrap-header to relative so that :before and :after does not goes outside */
#wrap-header {
  max-width: 100%;
  height: 400px;
  position: relative;
}

#wrap-header:before,
#wrap-header:after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
}

/* Set First Background Image */
#wrap-header:before {
  background: url("http://via.placeholder.com/850x450") center bottom no-repeat;
}

/* Set Second Background Image */
#wrap-header:after {
  background: url("http://via.placeholder.com/900x450") center top no-repeat;  
  opacity: 0.3; /* Set transparency as per your requirement */
}
<div id="wrap-header">

</div>

您可以简单地使用 background-size: 100% 50% 来完成,其中 100% 的第一个 value 表示 width image,第二个 height,设置为 50% 或总是 #wrap-header 的一半的 height:

#wrap-header {
  /*max-width: 100%; by default*/
  height: 400px;
  background-image: url('https://placeimg.com/1600/200/any'), url('https://placeimg.com/1600/201/any');
  background-repeat: no-repeat;
  background-position: bottom, top;
  background-size: 100% 50%;
}
<div id="wrap-header"></div>