半透明边框
·
Yin灏
导语
今天我来讲《CSS 揭秘》当中背景与边框章节的中的第一个效果,也是全书当中的第一个 CSS 效果。为了方便大家理解,我之后将以自己的方式去讲述。希望大家可以去看得懂,看不懂也不能怪我啊!(狗头)
今天我就用游戏原神当中珊瑚宫心海的表情包去演示,模拟在大海中,给心海加上一个半透明的外壳。
添加背景色
首先我们先打开编译器 VS Code,创建一个 HTML 文件,初始化背景色 background-colo
为 aqua
body {
background-color: aqua;
}
这样我们看到背景色就是青蓝色了
添加图片
接下来我们添加图片,也就是心海。
注意:图片的路径记得写你自己的。
<!-- 注意:图片的路径记得写自己的 -->
<img src="./心海表情包/母体.png" alt="心海">
就变成了这样子:
但是心海在左上角病号演示效果,所以我们可以为 body 添加一个我常用的可使子元素垂直居中的效果:
body {
width: 100vw;
height: 100vh;
background-color: aqua;
display: flex;
align-items: center;
justify-content: center;
}
添加边框
命名一个 CSS 类名为 xinhai
,然后赋予 img
标签上
<head>
<style>
body {
width: 100vw;
height: 100vh;
background-color: aqua;
display: flex;
align-items: center;
justify-content: center;
}
.xinhai {
border: 10px solid hsla(0, 0%, 100%, 0.5);
}
</style>
</head>
<body>
<!-- 注意:图片的路径记得写自己的 -->
<img class="xinhai" src="./心海表情包/母体.png" alt="心海">
</body>
效果如下:
我们成功给心海加上一个外壳。
你以为这样就完了吗?No! No! No!
完善
如果说这个外壳自带一个背景色的话,那就不一样了,比如我加个白色 white
:
.xinhai {
border: 10px solid hsla(0, 0%, 100%, 0.5);
background-color: white;
}
就变成:
可以看到我们的半透明外壳就不见了。 这是因为有个属性 background-clip 设置元素的背景(背景图片或颜色)延伸到边框,而这个属性默认为 border-box
,也就是默认是延伸到边框,半透明的边框也就透明了背景色的白色。
所以我需要将 background-clip 设置为 padding-box
背景延伸至内边距 padding
外沿。但不会绘制到边框处。
.xinhai {
border: 10px solid hsla(0, 0%, 100%, 0.5);
background-color: white;
background-clip: padding-box;
}
这样我们的小心海就再次拥有了半透明的外壳,又不怕在海里潜水了。(虽然心海的 PV 确实都是在水里什么都没有带)
完整代码
<head>
<style>
body {
width: 100vw;
height: 100vh;
background-color: aqua;
display: flex;
align-items: center;
justify-content: center;
}
.xinhai {
border: 10px solid hsla(0, 0%, 100%, 0.5);
background-color: white;
background-clip: padding-box;
}
</style>
</head>
<body>
<!-- 注意:图片的路径记得写自己的 -->
<img class="xinhai" src="./心海表情包/母体.png" alt="心海">
</body>