页面顶部5%的纯色为背景,其余部分为图像

问题描述 投票:0回答:1

是否有可能使用CSS将页面顶部5%的背景设置为纯色,并为剩余的65%和30%设置两个不同的背景图像?

这是我需要的外观:

enter image description here

css background gradient
1个回答
2
投票

编辑2:因此,有很多方法可以完成此任务。

  1. Pseudo elements:我认为这是最好的方法,因为它避免了标记中多余的元素,并且可以很好地控制缩放/裁剪。 下面的例子。

  2. [multiple container:的工作原理与伪元素类似,但缺点是标记中多余的元素。跨旧浏览器的最佳支持,但如今,伪元素得到了很好的支持。 下面的例子。

  3. [多背景:这可能适用于纯色或渐变,但是对于大多数图像,如果使用百分比作为尺寸,则缩放和裁切将成问题。 下面的例子。


1。伪元素

只需将::before::after伪元素添加到页面包装程序中,提供背景图像并相应地定位。

html, body {
  height: 100%;
  padding: 0;
  margin: 0;
}
.pagewrap {
  position: relative;
  height: 100%;
  background-color: green;
}
.pagewrap::before {
 content: "";
 position: absolute;
 top: 5%;
 left: 0;
 height: 65%;
 width: 100%;
 background-image: url("https://i.postimg.cc/nckTrT6T/21.jpg");
 background-size: cover;
 background-position: center;
}
.pagewrap::after {
 content: "";
 position: absolute;
 bottom: 0;
 left: 0;
 height: 30%;
 width: 100%;
 background-image: url("https://i.postimg.cc/qvDLXqB3/Optical-Illusion-Brain-washer-27.jpg");
 background-size: cover;
 background-position: center;
}
<div class="pagewrap">
</div>

2。多个容器

只需将上面示例中的伪元素替换为html中的容器div。

html, body {
  height: 100%;
  padding: 0;
  margin: 0;
}
.pagewrap {
  position: relative;
  height: 100%;
  background-color: green;
}
.mid65 {
 position: absolute;
 top: 5%;
 left: 0;
 height: 65%;
 width: 100%;
 background-image: url("https://i.postimg.cc/nckTrT6T/21.jpg");
 background-size: cover;
 background-position: center;
}
.btm30 {
 position: absolute;
 bottom: 0;
 left: 0;
 height: 30%;
 width: 100%;
 background-image: url("https://i.postimg.cc/qvDLXqB3/Optical-Illusion-Brain-washer-27.jpg");
 background-size: cover;
 background-position: center;
}
<div class="pagewrap">
    <div class="mid65"></div>
    <div class="btm30"></div>
</div>

3。多个背景图片

使用多个背景图片:background-image: url("image1.jpg"), url(image2.jpg);

然后使用相同的逗号分隔语法对于background-repeat: no-repeat, no-repeat; (相同值,无需重复)background-size: 100% 30%, 100% 65%;,等。

尽管背景位置是棘手的部分,因为它似乎不像人们期望的那样工作[[(Temani Afif在下面的评论中友善地提供了非常有用的link]。但这似乎达到了5%65%30%的预期结果:background-position: bottom left, 0% 15%;

编辑:用实际图像替换渐变,因此您可以看到此方法可能会导致图像拉伸问题。更适合纯色或渐变。

html, body { height: 100%; padding: 0; margin: 0; } .pagewrap { position: fixed; width: 100%; height: 100%; background-color: blue; background-image: url("https://i.postimg.cc/qvDLXqB3/Optical-Illusion-Brain-washer-27.jpg"), url("https://i.postimg.cc/nckTrT6T/21.jpg"); background-size: 100% 30%, 100% 65%; background-position: bottom left, 0% 15%; background-repeat: no-repeat; }
<div class="pagewrap"></div>
© www.soinside.com 2019 - 2024. All rights reserved.