css给div容器添加边角

在做大数据展示的时候,在不使用背景图片的情况下,为了让我们的界面显得更好看,我们经常会给一个div容器添加四个边角

先看一下效果:


效果图

下面,我将介绍我的实现方法

  1. 定义一个div容器,如div.container
  2. 在容器中定义三个子元素,比如有div.container-header div.container-main div.container-footer
  3. 接下来,给div.container-headerdiv.container-footer添加::before::after伪类,并将伪类中的元素分别设置成四个边角元素即可

首先,给出html代码,如上述描述,很简单

<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>CSS给div容器设置边角</title>

        <link rel="stylesheet" href="style.css" />
    </head>
    <body>
        <div class="container">
            <div class="container-header"></div>
            <div class="container-main"></div>
            <div class="container-footer"></div>
        </div>
    </body>
</html>

接下来,是div容器的css设置(用less写的),也很简单(注释已经写的很清楚了哦),如下

* {
    margin: 0;
    padding: 0;
}

.container {
    width: 400px;
    height: 200px;
    margin: 40px;
    box-sizing: border-box;
    // 一定要为 .container 设置 position: relative
    // 这样 .container-header 和 .container-footer 中的内容就是相对于 .container 的
    position: relative;

    display: flex;
    flex-direction: column;

    .container-main {
        // 设置 flex-grow: 1,让 .container-main 撑满整个容器
        flex-grow: 1;
    }

    .container-header {
        &::before {
            content: '';
            // .container 设置了 position: relative 之后,
            // 这里的 position: absolute 就是相对于 .container 的了
            // 这样之后,top: 0; left: 0; 自然就是 .container 的左上角了
            position: absolute;
            // 给伪类内容设置宽高,这样边框 border 的宽高也就是这个了
            width: 10px;
            height: 10px;
            top: 0;
            left: 0;
            border-top: 2px solid #02a6b5;
            border-left: 2px solid #02a6b5;
        }
        &::after {
            content: '';
            position: absolute;
            width: 10px;
            height: 10px;
            top: 0;
            right: 0;
            border-top: 2px solid #02a6b5;
            border-right: 2px solid #02a6b5;
        }
    }
    .container-footer {
        &::before {
            content: '';
            position: absolute;
            width: 10px;
            height: 10px;
            bottom: 0;
            left: 0;
            border-bottom: 2px solid #02a6b5;
            border-left: 2px solid #02a6b5;
        }
        &::after {
            content: '';
            position: absolute;
            width: 10px;
            height: 10px;
            bottom: 0;
            right: 0;
            border-bottom: 2px solid #02a6b5;
            border-right: 2px solid #02a6b5;
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容