使用单个 div 在 CSS 中创建伪 3D 效果
HTML
CSS
最近我偶然读到一篇由 Bradley Taunt 撰写的文章,题为《用 CSS 制作伪 3D 元素》。这篇文章非常浅显易懂,教你如何使用不超过两个 div 元素来制作伪 3D 效果。
我决定只用一个 div 来重现类似的效果,结果应该已经很接近了。那么,我们来看看如何实现它。
如上所述,我们只需要一个div
。在 HTML 中,添加一个 div 并赋予其 类circle
。
<div class="circle"></div>
div
现在,让我们开始编写CSS 。首先,我们将以下样式添加到circle
.circle{
height: 400px;
width: 400px;
background: linear-gradient(#f00202 0%, #bd0404 10%, #7d0404 50%, #4a0202 100%);
border-radius: 50%;
}
添加一些flexbox
属性,使页面body
垂直和水平居中。circle
body{
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
现在,我们需要再添加一个圆圈,将其放置在 main 元素内部circle
。这个内圆主要负责产生所需的伪 3D 效果。为了创建内圆,我们将使用::before
伪元素。
.circle::before{
content: "";
height: 360px;
width: 360px;
background: linear-gradient(#f06060 0%, #a30505 60%, #4d0202 100%);
}
flexbox
通过向类添加必要的属性,将其准确地放置在主圆的中心center
。
.circle{
...
...
display: flex;
justify-content: center;
align-items: center;
}
为了获得最终的 3D 效果,请将以下两个 CSS 属性添加到::before
伪元素。
.circle::before{
...
...
border-radius: 50%;
filter: blur(18px);
}
最后,让我们给身体添加一个background-color
,#990000
即红色。
body{
...
...
background: #990000;
}
等等。我们还缺少最后一件事——阴影。我们将使用::after
伪元素来实现它。
.circle::after{
content: '';
position: absolute;
width: 100%;
height: 60px;
border-radius: 50%;
background: rgba(0,0,0,0.6 );
bottom: -60px;
z-index: -1;
filter: blur(10px);
}
注意,伪元素的类::after
名为。请确保它相对于主 div 的定位与 类相关。因此,给主 div 指定一个类。position
absolute
circle
position
relative
.circle{
...
...
position: relative;
}
以下是最终代码
HTML
<div class="circle"></div>
CSS
body{
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background: #990000;
}
.circle{
height: 400px;
width: 400px;
background: linear-gradient(#f00202 0%, #bd0404 10%, #7d0404 50%, #4a0202 100%);
border-radius: 50%;
display: flex;
justify-content: center;
align-items: center;
position: relative;
}
.circle::before{
content: "";
height: 360px;
width: 360px;
background: linear-gradient(#f06060 0%, #a30505 60%, #4d0202 100%);
border-radius: 50%;
filter: blur(18px);
}
.circle::after{
content: '';
position: absolute;
width: 100%;
height: 60px;
border-radius: 50%;
background: rgba(0,0,0,0.6 );
bottom: -60px;
z-index: -1;
filter: blur(10px);
}