分割线是网页中比较常见的一类设计了,比如说知乎的更多回答
这里的自适应是指两边的横线会随着文字的个数和父级的宽度自适应
偷偷的看了一下知乎的实现,很显然是用一块白色背景覆盖的,加一点背景就露馅了
心想:知乎的前端也不怎么样? 可能别人的重点不在这些上面吧
下面列举几种更好的实现方式,不会露馅的那种
1.伪元素+transform:translateX(-100%);
主要原理是设置文本居中text-align: center;,然后给定两个伪元素,分别绝对定位,那么此时伪元素也是跟随着水平居中的,设置足够的宽度,然后把左边的往左位移100%就可以了,父级记得超出隐藏。
具体实现如下
html结构为
<div class="title">我是分割线</div>
css样式为
.title{
position: relative;
text-align: center;
overflow: hidden;
font-size: 14px;
color: #999;
}
.title::before,.title::after{
content: '';
display: inline-block;
width: 100%;
height: 1px;
position: absolute;
background: #ccc;
top: 50%;
}
.title::before{
margin-left: -10px;
transform: translateX(-100%);
}
.title::after{
margin-left: 10px;
}
See the Pen CSS分隔线 (伪元素+transform) by XboxYan (@xboxyan) on CodePen.
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
2.伪元素+flex
这个比较好理解了,设置display:flex,然后两个伪元素分别铺满剩余空间。
具体实现如下
html结构为
<div class="title">我是分割线</div>
css样式为
.title{
display: flex;
align-items: center;
font-size: 14px;
color: #999;
}
.title::before,.title::after{
content: '';
flex: 1;
height: 1px;
background: #ccc;
}
.title::before{
margin-right: 10px;
}
.title::after{
margin-left: 10px;
}
See the Pen CSS分隔线 (伪元素+flex) by XboxYan (@xboxyan) on CodePen.
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
3.伪元素+box-shadow/outline+clip-path
同样利用text-align: center使文本和伪元素居中,然后生成足够大的box-shadow或者outline,由于不支持单个方向,所以用clip-path或者clip裁剪掉
具体实现如下
html结构为
<div class="title">我是分割线</div>
css样式为
.title{
text-align: center;
font-size: 14px;
color: #999;
overflow: hidden;
}
.title::before,.title::after{
content: '';
display: inline-block;
width: 0;
height: 1px;
box-shadow: 0 0 0 9999px #ccc;
vertical-align: middle;
}
.title::before{
margin-right: 10px;
clip-path: polygon(0 0, -9999px 0, -9999px 100%, 0 100%);
}
.title::after{
margin-left: 10px;
clip-path: polygon(0 0, 9999px 0, 9999px 100%, 0 100%);
}
See the Pen CSS分隔线 (伪元素+box-shadow/outline+clip-path) by XboxYan (@xboxyan) on CodePen.
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>