在做大數(shù)據(jù)展示的時(shí)候,在不使用背景圖片的情況下,為了讓我們的界面顯得更好看,我們經(jīng)常會(huì)給一個(gè)div容器添加四個(gè)邊角
先看一下效果:

效果圖
下面,我將介紹我的實(shí)現(xiàn)方法
- 定義一個(gè)div容器,如
div.container - 在容器中定義三個(gè)子元素,比如有
div.container-headerdiv.container-maindiv.container-footer - 接下來,給
div.container-header和div.container-footer添加::before和::after偽類,并將偽類中的元素分別設(shè)置成四個(gè)邊角元素即可
首先,給出html代碼,如上述描述,很簡(jiǎn)單
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CSS給div容器設(shè)置邊角</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設(shè)置(用less寫的),也很簡(jiǎn)單(注釋已經(jīng)寫的很清楚了哦),如下
* {
margin: 0;
padding: 0;
}
.container {
width: 400px;
height: 200px;
margin: 40px;
box-sizing: border-box;
// 一定要為 .container 設(shè)置 position: relative
// 這樣 .container-header 和 .container-footer 中的內(nèi)容就是相對(duì)于 .container 的
position: relative;
display: flex;
flex-direction: column;
.container-main {
// 設(shè)置 flex-grow: 1,讓 .container-main 撐滿整個(gè)容器
flex-grow: 1;
}
.container-header {
&::before {
content: '';
// .container 設(shè)置了 position: relative 之后,
// 這里的 position: absolute 就是相對(duì)于 .container 的了
// 這樣之后,top: 0; left: 0; 自然就是 .container 的左上角了
position: absolute;
// 給偽類內(nèi)容設(shè)置寬高,這樣邊框 border 的寬高也就是這個(gè)了
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;
}
}
}