奔走在前端工作战场的小伙伴们,关于在文字俩侧加横线的情况一定常常有遇到,听到这个我们首先想到的方法是什么呢,定位?背景图片?伪类?还是浮动呢....跳跳大路通罗马我想可能每个人都有自己的解决方案.今天我总结一下我自己方法.
第一种:背景是纯色的实现方法:
就是下边这种效果
这个应该是对每个人来说都比较容易一种方法是,我们可以用一个空的标签,来写这条横线,之后进行布局。当然也可以用背景图,切一个中间透明,两边白条的图片。可以用以下代码来实现
HTML:
<div class="textBg">
<h2 class="text">
<span class="textTitle">我是标题</span>
</h2>
<span class="line"></span>
</div>
CSS部分:
/*纯背景实现原理代码*/
.textBg{
background: cadetblue;
500px;
height: 300px;
margin:0 auto;
background-size: cover;
position: relative;
}
.text{
position: absolute;
top: 70px;
left:50%;
150px;
margin-left: -75px;
margin-top: 50px;
z-index: 2;
}
.textTitle{
/*这里需要设置设置和背景颜色一样的颜色。*/
background:cadetblue;
padding:0px 20px;
}
.line{
display: inline-block;
500px;
height: 0px;
border: 2px solid #fff;
position: absolute;
top:130px;
left: 50%;
margin-left: -250px;
}
代码解析:
把标题和线条定位左右居中,上下靠上部分,用z-index将文字层级放置线条上方,在给标题使用和背景色一样的背景色。padding设置左右值撑开空隙。上边的方法取了个巧,利用背景色一致看不出差别,这种方法当然有一定的局限性;
<----分割线----->重点看下边
第二种:背景是花色的:
就是要实现下边下边这种效果,背景为图片,当然也是可以用多种方法来实现,以下我介绍我总结的一种
以下是我的代码
html部分
<div class="text_bg">
<h2 class="text">
<span class="text_title">我是标题请输入</span>
</h2>
css部分
/*背景图片实现原理代码*/
.text_bg{
background: url(img/6.png) no-repeat;
/*background: cadetblue;*/
700px;
height: 400px;
margin:0 auto;
background-size: cover;
position: relative;
}
.text{
position: absolute;
top: 70px;
left:50%;
600px;
margin-left: -300px;
text-align: center;
}
/*伪元素实现*/
.text_title:before{
display: inline-block;
150px;
height: 0;
border: 2px solid white;
position: absolute;
content: "";
right: 30px;
top: 15px;
}
.text_title:after{
display: inline-block;
150px;
height: 0;
border: 2px solid white;
position: absolute;
content: "";
left: 30px;
top: 15px;
}