仅使用两个 CSS 属性创建玻璃效果
创建背景
背景的话是在网上找的一个渐变背景。
我们先创建一个html
文件然后给个div
给个类名
<div class="container">
</div>
然后我们把以下样式添加上去
.container {
height: 100vh;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
position: relative;
background: #ff00cc;
background: -webkit-linear-gradient(
to right,
#333399,
#ff00cc
);
background: linear-gradient(
to right,
#333399,
#ff00cc
);
}
我们确保容器占据整个屏幕。我们将容器内的内容对齐到中心。
linear-gradient
我们还使用该属性将渐变添加到背景中。
-webkit-linear-gradient
用于某些浏览器。如果浏览器不支持渐变,我们会提供默认颜色。
线性梯度
linear-gradient 属性接受一个方向和一个颜色列表。可以使用to
关键字指定方向。颜色是使用rgb
orrgba
函数指定的。该rgb
函数接受红色、绿色和蓝色的三个值。该rgba
函数采用附加值 alpha。alpha 值指定颜色的不透明度。alpha 值可以是 0 到 1 之间的任何值。0 表示颜色完全透明,1 表示完全不透明。
添加圆圈
我们使用 class和创建两个div
元素。circle1``circle2
<div class="circle1"></div>
<div class="circle2"></div>
我们将以下样式添加到圆圈中。
.circle1,
.circle2 {
background: white;
background: linear-gradient(
to right bottom,
rgba(255, 255, 255, 0.9),
rgba(255, 255, 255, 0.1)
);
height: 20rem;
width: 20rem;
position: absolute;
border-radius: 50%;
}
圆圈的高度和宽度为 20rem。我们给它们一个绝对位置,以便它们可以相对于容器定位。我们给它们一个 50% 的边界半径,这样它们就变成了圆形。
我们为圆圈的背景添加了一个线性渐变。如果浏览器不支持渐变,我们给圆圈一个默认颜色。
定位圆圈
为了定位圆圈,我们将以下样式添加到圆圈中。
.circle1 {
top: 10%;
left: 15%;
transform: translate(-10%, -10%);
}
.circle2 {
top: 70%;
left: 80%;
transform: translate(-50%, -50%);
}
我们给第一个圆圈的顶部值为 10%,左侧值为 10%。它将圆圈从顶部移动 10%,从左侧移动 10%。然后我们使用该transform
属性将圆在 x 和 y 方向上平移 -10%。这样做是为了使圆圈相对于容器的左上角定位。
第二个圆圈也做了类似的事情。
添加玻璃卡
我们在容器中创建一个div
带有类的元素。glass-card
我们将以下样式添加到玻璃卡中。
.glass-card {
background: white;
background: linear-gradient(
to right bottom,
rgba(255, 255, 255, 0.4),
rgba(255, 255, 255, 0.2)
);
backdrop-filter: blur(1rem);
width: 60%;
height: 60%;
z-index: 1;
display: flex;
justify-content: center;
align-items: center;
border-radius: 5rem;
box-shadow: 0 0 1rem rgba(0, 0, 0, 0.2);
}
他们在这里.... 用于创建玻璃效果的两个属性。
linear-gradient
backdrop-filter
线性渐变创建一个半透明的白色背景。
linear-gradient()
函数用于创建一个表示两种或多种颜色线性渐变的图片。
创建一个线性渐变,需要指定两种颜色,还可以实现不同方向(指定为一个角度)的渐变效果,如果不指定方向,默认从上到下渐变。
该backdrop-filter
属性用于将模糊和饱和度等图形效果应用于元素的背景。大多数现代浏览器都支持它。Internet Explorer 不支持它。
我们添加了一个模糊效果,其值可以根据需要更改。
为了确保圆圈在玻璃后面,我们添加了z-index
将卡片移动到圆圈上方的属性。
添加内容
我们在玻璃卡片上添加一个简单的标题吧。
<h1>Hello World</h1>
我们为标题添加了一些样式这样看起来会更加的完美。
.glass-card h1 {
font-size: 5rem;
color: white;
text-align: center;
font-weight: 700;
letter-spacing: 0.5rem;
text-shadow: 0 0 1rem rgba(0, 0, 0, 0.2);
}
总结
我们就使用了两个属性来完成了我们的玻璃效果,你也赶紧去试试吧。
转载自:https://juejin.cn/post/7148987512982077453