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

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

这就是我需要的样子:

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

seaxon 回答:以纯色为背景,占页面顶部5%,其余部分为图像

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

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

  2. 多个容器:与伪元素一样工作,但缺点是标记中多余的元素。跨旧浏览器的最佳支持,但如今,伪元素得到了很好的支持。 下面的示例。

  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>

本文链接:https://www.f2er.com/3069387.html

大家都在问