css 如何重复一个裁剪的图像作为一个垂直平铺的背景?

evrscar2  于 2023-06-25  发布在  其他
关注(0)|答案(2)|浏览(166)

我试图创建一个垂直平铺的背景,通过裁剪背景图像的顶部50 px,并只使用该裁剪部分。但是,下面提供的代码示例没有按预期运行。尽管为<div class="content">分配了更高的z索引,但它也被裁剪。另外,图像的剪切部分不是重复的。
虽然我已经设法通过删除代码中的注解获得了所需的结果(如下面所示:https://jsfiddle.net/jamacoe/1ej3k80o/3/),它涉及重复<div class="clipped">容器。有没有一种方法可以只使用一个高度为100%的<div class="clipped">容器来实现这一点?我将非常感谢任何见解或替代方法,以达到预期的效果。谢谢你!

.outer {
  border: 1px solid red;
  height: 150px;
  overflow: hidden;
  position: strict;
}
.clipped {
   background-image: url("https://source.unsplash.com/featured/?nature");
   clip-path: inset(1 0 calc(100% - 51px) 0);
   background-repeat: repeat-y;
   height: 50px;
   z-index: -1;
}
.content {
  position: absolute;
  top: 0;
  z-index: 1;
}
p {
  color: white;
  background-color: rgba(255, 255, 255, 0.25);
}
<div class=outer>
  <div class=clipped></div>
  <!-- div class=clipped></div>
  <div class=clipped></div -->
  
  <div class=content>
    <p>content 1</p>
    <p>content 2</p>
    <p>content 3</p>
    <p>content 4</p>
  </div> 
</div>
e4eetjau

e4eetjau1#

你不能用clip-path来做这件事,就像上面所示的那样,它可以剪切元素中的所有内容。
如你所知,有3个重复需要你可以做这一切与背景,使用的事实,即第一个背景图像将覆盖以下背景图像等。
所以在这个片段中,它首先在100 px处写入底部背景,下一个在50 x处写入,最后一个在0 px处写入,
当然,你可以使用%s来使它更通用/响应更快,但是如果所需的“条纹”数量改变了,你需要添加更多的背景图像。

<style>
    .bg {
    border: 1px solid red;
    display: inline-block;
    width: 100vw;
    height: 150px;
    background-image: url("https://source.unsplash.com/featured/?nature"), url("https://source.unsplash.com/featured/?nature"), url("https://source.unsplash.com/featured/?nature");
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: 0 100px, 0 50px, 0 0;
</style>
<div class="bg">

</div>
hivapdat

hivapdat2#

可能不是最好的方法,也不是你想要的,但你可以在图形编辑器中手动创建一堆这些,例如Figma,然后使用js创建一个CSS类列表,每个CSS类都有不同的背景图像,然后使用math.random()随机选择一个。
直接从网站上剪辑它们也可能会损害性能很多,因为Unplash图像是.jpg图像,但您可以使用更快的.webp图像,例如通过转换它们here

相关问题