1. 知识储备
对于如何使用 CSS 制作一个半透明边框,首先你要知道 background-clip
这个属性
background-clip
: 设置元素的背景(背景图片或颜色)是否延伸到边框、内边距盒子、内容盒子下面(即用来确定背景绘制区域)
可以去 MDN 文档中 background-clip 具体学习一下它的用法。
它有着以下四个值:
border-box
: [ 默认值 ] 背景绘画边框外沿(在边框下层,即这个元素会遮挡住背景)padding-box
: 背景延伸至内边距(padding)外沿不会绘制到边框处content-box
: 背景被裁剪至内容区(content box)外沿text
: 背景被裁剪成文字的前景色
2. 具体实现
先建立两个盒子出来
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>半透明边框</title>
<style>
.box1 {
display: flex;
justify-content: center;
align-items: center;
margin: 0 auto;
height: 300px;
width: 300px;
background-color: gray;
}
.box2 {
height: 150px;
width: 200px;
background-color: aqua;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2 ">
</div>
</div>
</body>
</html>
此时效果如下:
这个时候,要给里面那个盒子加一个半透明边框,可以给它增添一个边框样式,里面使用 background-clip
属性。
/* 设置边框的大小和颜色---半透明 */
border: 10px solid hsla(0, 0%, 100%, 0.5);
/* 设置 background-clip 属性的值为 padding-box,背景就会延伸到内边距的外沿 */
background-clip: padding-box;
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>半透明边框</title>
<style>
.box1 {
display: flex;
justify-content: center;
align-items: center;
margin: 0 auto;
height: 300px;
width: 300px;
background-color: gray;
}
.box2 {
height: 150px;
width: 200px;
background-color: aqua;
/* background-clip 属性书写位置注意!!!
写于该元素的背景颜色的后面,
如果写于前面,则 background-clip 属性不会产生作用
*/
border: 10px solid hsla(0, 0%, 100%, 0.5);
background-clip: padding-box;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2">
</div>
</div>
</body>
</html>
这样,我们就实现了一个半透明的边框了,效果如下:
3. 总结
实现半透明边框:
- 设置边框的 大小 和 颜色 - - - 半透明
border: 10px solid hsla(0, 0%, 100%, 0.5);
- 设置
background-clip
属性的值为padding-box
,使背景延伸到内边距的外沿
background-clip: padding-box;
Tips:
根元素具有不同的背景绘制区域,因此在对其指定时,
background-clip
属性无效
如果存在背景,背景始终绘制在边框后面