如何制作出首页的渐变图片
使用 linear-gradient 函数
CSS
.easy-demo {
width: 100%;
height: 40vh;
background: linear-gradient(to top, rgba(255, 255, 255, 1), rgba(255, 255, 255, 0)),url(/images/hero-bg.png);
}
这种方式已经可以实现大多数的渐变效果了,不过这种渐变是整个背景从头到尾一起渐变的,如果我们想要在图片的底部渐变,那么就需要使用到 ::after
伪元素了。
::after
伪元素
首先介绍一下 ::after
这个伪元素,它会在元素的最后面添加一个内容,并且可以设置它的样式,比如颜色、背景、边框等等。
例如现在有一个这个盒子,我们加上一个伪元素:
HTML
<div class="after-demo">这是一个原始的测试盒子。</div>
CSS
.after-demo {
border: 1px solid rgb(36, 31, 31);
}
.after-demo::after {
content: '这是追加的一个伪元素';
color: #fff;
background-color: red;
}
那么这个盒子的样式就是:
这是一个原始的测试盒子。
::after
伪元素用于在目标元素的最后面插入内容。这个内容可以是文本、图标,甚至是一个空的内容 content: ''
。通过设置 ::after
的样式,我们可以实现一些视觉效果,比如遮罩、渐变、装饰等。
HTML
<div class="background-demo">
</div>
CSS
.background-demo {
width: 100%;
height: 40vh;
background: url('/images/hero-bg.png') no-repeat;
}
.background-demo::after {
content: '';
width: 100%;
height: 150px;
background: linear-gradient(to bottom, transparent, var(--vp-c-bg-soft));
display: block;
}
核心的渐变样式就是:
CSS
.background-demo::after {
content: '';
width: 100%;
height: 150px;
background: linear-gradient(to bottom, transparent, var(--vp-c-bg-soft)); /*
display: block;
}
调整渐变的位置
接下来就把这个渐变的位置移到下方就好啦,这里有两种方式,一种是 flex 弹性布局,另一种是 position 定位。
CSS
.background-demo {
width: 100%;
height: 40vh;
background: url('/images/hero-bg.png') no-repeat center/cover; /* 背景图片 */
display: flex;
flex-direction: column;
justify-content: flex-end;
}
.background-demo::after {
content: '';
width: 100%;
height: 150px;
background: linear-gradient(to bottom, transparent, var(--vp-c-bg-soft));
}
CSS
.hero-section {
height: 40vh;
width: 100%;
background-image: url('/images/hero-bg.png');
background-size: cover;
background-position: center;
position: relative;
overflow: hidden;
}
.hero-section::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 150px; /*渐变区域高度*/
background: linear-gradient(to bottom,
transparent,
var(--vp-c-bg-soft));
}
flex 弹性布局:
position 定位: