如何在每一侧都有相同的背景图像?

How to have the same background image on each each side?

我在查看背景图片选项时找不到 CSS background-repeat 属性 符合我想要的设计。我想要的设计是这样的:

问题:

我想要的设计正好是 2 张像这样的图像,它们与 window 的距离相似。 有什么方法可以在 CSS 中实现这一点,并且仍然将图像保留为背景而不将它们放在 <img> 标签中?

这是一个代码片段,您可以使用它来将 CSS 应用于:

.content{
height: 300px;
width: 1000px;
background-color: grey;
background-image: url("https://lh4.ggpht.com/mJDgTDUOtIyHcrb69WM0cpaxFwCNW6f0VQ2ExA7dMKpMDrZ0A6ta64OCX3H-NMdRd20=w300-rw")
}
<div class="content">
 </div>

您可以简单地在背景中使用图像两次并根据需要调整 position/size(您将有 多个 背景)。您也可以将背景颜色放在相同的 属性.

注意顺序。 第一个背景将在顶部,所以背景颜色应该是最后一个,这样它就不会覆盖图像。

.content {
  height: 300px;
  width: 1000px;
  background:  
  url("https://lh4.ggpht.com/mJDgTDUOtIyHcrb69WM0cpaxFwCNW6f0VQ2ExA7dMKpMDrZ0A6ta64OCX3H-NMdRd20=w300-rw") left/auto 100% no-repeat, 
  url("https://lh4.ggpht.com/mJDgTDUOtIyHcrb69WM0cpaxFwCNW6f0VQ2ExA7dMKpMDrZ0A6ta64OCX3H-NMdRd20=w300-rw") right/auto 100% no-repeat,
  grey;
}
<div class="content">
</div>

或者你可以单独保留 background-color 但你必须在多个背景之后定义它,否则它会被背景覆盖 属性:

/* This is correct */
.content {
  height: 300px;
  width: 1000px;
  background:  
  url("https://lh4.ggpht.com/mJDgTDUOtIyHcrb69WM0cpaxFwCNW6f0VQ2ExA7dMKpMDrZ0A6ta64OCX3H-NMdRd20=w300-rw") left/auto 100% no-repeat, 
  url("https://lh4.ggpht.com/mJDgTDUOtIyHcrb69WM0cpaxFwCNW6f0VQ2ExA7dMKpMDrZ0A6ta64OCX3H-NMdRd20=w300-rw") right/auto 100% no-repeat;
  background-color:grey;
}
/* This is not correct as background-color will have no effect*/
.content-alt {
  height: 300px;
  width: 1000px;
  background-color:grey;
  background:  
  url("https://lh4.ggpht.com/mJDgTDUOtIyHcrb69WM0cpaxFwCNW6f0VQ2ExA7dMKpMDrZ0A6ta64OCX3H-NMdRd20=w300-rw") left/auto 100% no-repeat, 
  url("https://lh4.ggpht.com/mJDgTDUOtIyHcrb69WM0cpaxFwCNW6f0VQ2ExA7dMKpMDrZ0A6ta64OCX3H-NMdRd20=w300-rw") right/auto 100% no-repeat;

}
<div class="content"></div>
<div class="content-alt"></div>

更多详情:

您还可以考虑另一种用于多背景的语法。上面我用了 shorthand 一个,但是你可以分开属性。如果您将拥有许多共享相同值的图像(例如您的情况下的大小和重复),这将很有用。这也将删除 background-color 限制,例如,您可以轻松地将背景颜色与另一个 class:

一起应用

.content {
  height: 300px;
  width: 1000px;
  /* you can put back this on the top as there is no more background property used */
  background-color:grey;
  background-image:  
  url("https://lh4.ggpht.com/mJDgTDUOtIyHcrb69WM0cpaxFwCNW6f0VQ2ExA7dMKpMDrZ0A6ta64OCX3H-NMdRd20=w300-rw"), 
  url("https://lh4.ggpht.com/mJDgTDUOtIyHcrb69WM0cpaxFwCNW6f0VQ2ExA7dMKpMDrZ0A6ta64OCX3H-NMdRd20=w300-rw");
  background-size:auto 100%; /* Same for both no need to define twice */
  background-position:left,right; /* we respect the same order as background-image*/
  background-repeat:no-repeat; /* Same for both no need to define twice */

}
<div class="content">
</div>