CSS制作一个半透明边框

CSS制作一个半透明边框


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. 总结

实现半透明边框:

  1. 设置边框的 大小 和 颜色 - - - 半透明
border: 10px solid hsla(0, 0%, 100%, 0.5);
  1. 设置 background-clip 属性的值为 padding-box,使背景延伸到内边距的外沿
background-clip: padding-box;

Tips:

根元素具有不同的背景绘制区域,因此在对其指定时, background-clip 属性无效
如果存在背景,背景始终绘制在边框后面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值