【CSS】设置 border 长度

场景举例

如何实现 在线课程 字体下方的 短横线 样式效果

思考过程

1.常规方案

看到这样的样式效果,大多数人首先想到的一定是 border-bottom 吧,但是真正写在 css 中,你会发现,效果是这样的

实现了,却又好像没实现,无法设置长度,那么下面我们试着换一种思路去实现这个效果

2.优化方案

我们不要把这个短横线看做 border ,使用 伪元素 实现,可以随意更改大小、宽度、长度等,非常的方便

伪元素

用于设置元素指定部分的样式,可用于设置元素的首字母、首行的样式,在元素的内容之前或之后插入内容等

1
2
3
selector::pseudo-element {
property: value;
}

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.box h1::after {
/* 必须设置 content 属性才能生效 */
content: '';
/* border 宽度 */
width: 1000px;
/* border 高度 */
height: 2px;
background-color: #cccccc;
/* border 位置 absolute(绝对定位) */
position: absolute;
left: 295px;
top: 705px;
bottom: 918px;
/* 自动内减 */
box-sizing: border-box;
}

通用格式

抽象上述代码为通用格式,日后可应用在其他场景下

1
2
3
4
5
6
7
8
9
10
11
selector:after {
content: '';
position: absolute;
left: 0;
top: 0;
bottom: 0px;
right: 0;
height: 0px;
width: 0px;
background-color: ;
}

参考资料:

  • border-position属性详解