边框内圆角,你会怎么实现

193 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第31天,点击查看活动详情

有时我们需要一个容器,只在内侧有圆角,而边框的四个角仍然保持直角状态:

image.png

一般拿到这种需求,我们可能会这样写:

<!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>Document</title>
    <style>
        .border {
            width: 200px;
            height: 80px;
            background-color: #655;
            padding: 10px;
        }

        .content {
            width: 100%;
            height: 100%;
            background-color: tan;
            border-radius: 10px;
        }
    </style>
</head>

<body style="padding: 100px">
    <div class="border">
        <div class="content"></div>
    </div>
</body>

</html>

利用两个div可以很轻松搞定。那么如果不用两个div,只用一个可以吗?让我们来打开自己的脑洞吧~

1. 利用伪元素

.demo {
    position: relative;
    width: 200px;
    height: 80px;
    background-color: #655;
}
.demo::before {
    content: '';
    position: absolute;
    width: 180px;
    height: 60px;
    top: 10px;
    left: 10px;
    background-color: tan;
    border-radius: 10px;
}

image.png

同理伪元素after也能达到想同的效果。

2. 利用阴影和描边

.demo {
    width: 180px;
    height: 60px;
    background-color: tan;
    outline: 10px solid #655;
    border-radius: 10px;
    box-shadow: 0 0 0 10px #655;
}

image.png

哇,神奇,这凭啥就能实现如此效果了?我有点不解,别急,咱们分解下看看是怎么回事?

我们先不加阴影:

image.png

可以看到outline作用是给外围加上一圈描边,有意思的是,这个描边始终是直角的,也没办法设置成圆角,不过在这边反倒有了奇效。

加上阴影,不给描边:

image.png

索达寺内!两者组合一下,效果成了!

不过这个实现方式有局限性,假如我们的圆角比较大,但是边框比较小,就会出现这种情况:

demo12.gif

所以要想使用描边加阴影实现内圆角效果,需先计算阴影扩张的距离是否超过了描边的大小。否则就是出现上述那种尴尬的情况。

参考

《CSS揭秘》纸质书本

往期精彩

# 扫福开始了,自己写个福来扫啊~

# 从零开始做一个贪吃蛇游戏,会vue就行

# 血条消失术?用css教你实现

# 用canvas生成一个佛系头像

# 我用一个div就画出了一个大西瓜~