如何在CSS中并排设置图像背景

  • 本文关键字:设置 图像 背景 CSS css
  • 更新时间 :
  • 英文 :


我试图让一个容器有两个并排的背景图像,这样我就可以将一些文本放在这两个容器的顶部。到目前为止,我只能得到一个背景图像来显示。如何将它们滑开?

HTML:

<article class="about-us">
<div class="staff">
<h2 class="about-us-content">Let us share your story.</h2>
</div>
</article>

CSS:

.staff {
height: 377px;
width: 377px;
background-image: url(Image1), url(Image2);
background-position: top left, bottom right;
background-repeat: no-repeat;
display: flex;
align-items: center;
justify-content: center;
}

您只需添加:

background-size: 50% 100%;

请检查以下代码段。

但请添加一张关于你到底想要什么的截图。

.staff {
height: 377px;
width: 377px;
background-image: url("https://cdn.pixabay.com/photo/2021/01/23/13/01/hills-5942468_1280.jpg"), url("https://cdn.pixabay.com/photo/2020/04/28/21/01/wallpaper-5106327_1280.jpg");
background-position: top left, bottom right;
background-repeat: no-repeat;
background-size: 50% 100%;
display: flex;
align-items: center;
justify-content: center;
}
<article class="about-us">
<div class="staff">
<h2 class="about-us-content">Let us share your story.</h2>
</div>
</article>

.staff {
width: 500px;
background: url(https://via.placeholder.com/250x100), url(https://via.placeholder.com/250x100);     
background-position: top left, top right;
background-repeat: no-repeat;
display: flex;
align-items: center;
justify-content: center;
}
<article class="about-us">
<div class="staff">
<h2 class="about-us-content">Let us share your story.</h2>
</div>
</article>

你可以在另一个问题中找到更多的解决方案:我可以使用CSS获得多个背景图像吗?

如果希望精确控制图像的显示方式,可以使用前后伪选择器。

.staff {
height: 377px;
width: 377px;
display: flex;
align-items: center;
justify-content: center;
position: relative;
}
.about-us-content {
position: relative;
z-index: 2;
}
.staff::before,
.staff::after {
position: absolute;
content: "";
width: 50%;
height: 100%;
top: 0;
background-size: cover;
background-position: center;
}
.staff::before {
background-image: url("https://images.unsplash.com/photo-1531603845872-e4a07041f521?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=632&q=80");
left: 0;
}
.staff::after {
background-image: url("https://images.unsplash.com/photo-1601248318142-f3cd4bb230b4?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=642&q=80");
left: 50%;
}
<article class="about-us">
<div class="staff">
<h2 class="about-us-content">Let us share your story.</h2>
</div>
</article>