文字两侧加横线的解决方案

文字两侧加横线的需求你遇到过吗?在参与的项目中我遇到过这种需求,总结了一下,目前分为两种:bash

一,文字所在的背景是纯色,单一颜色;spa

二,文字所在背景是花色,或者是背景图片

给你一些时间,思考一下:

脑海闪过了什么?定位,浮动,背景图片,伪元素。。。仍是大脑一片空白?

条条大路通罗马,相信给你足够的时间,静静的坐在开着空调的房间里,你会获得本身的实现方法。code

先看第一种,背景纯色的实现方案。orm

用的一个方法是用一个空的标签,来写这条横线。固然也能够用背景图,切一个中间透明,两边白条的图片。也能够使用伪元素。before after先后夹击。cdn

在背景为图片的时候使用了伪元素这种方法,我的感受伪元素这个东西真的是太强大了。blog

废话不说上代码:图片

HTML:string

<div class="onpure_bg">
    <h2 class="onpure">
        <span class="onpure_title">标题在此</span>
    </h2>
    <span class="line"></span>

</div>
复制代码

CSS:it

/*纯背景实现原理代码*/
.onpure_bg{
    background: #ccc;
    width: 700px;
    height: 400px;
    margin:0 auto;
    background-size: cover; 
    position: relative;
}
.onpure{
    position: absolute;
    top: 70px;
    left:50%;
    width: 150px;
    margin-left: -75px;
    margin-top: 50px; 
    z-index: 1
}
.onpure_title{
/*关键点:设置和背景颜色同样的颜色。*/
    background:#ccc;
    padding:0px 20px; 
}
.line{
    display: inline-block;
    width: 500px;
    height: 0px;
    border: 2px solid #fff;
    position: absolute;
    top:130px;
    left: 50%;
    margin-left: -250px;
}

复制代码

代码解析:io

把标题和线条定位左右居中,上下靠上部分,用z-index将文字层级放置线条上方,在给标题使用和背景色同样的背景色。padding设置左右值撑开空隙。

It is so easy!

再来看背景为图片的实现方法,很显然,上边的方法取了个巧,利用背景色一致看不出差异。换成一张有复杂的背景图案的图片,这种方法就失效,咱们借助伪元素来实现。

代码

HTML

<div class="onimg_bg">
    <h2 class="onimg">
        <span class="onimg_title">标题在此</span>
    </h2>
</div>
复制代码

CSS

/*背景图片实现原理代码*/

.onimg_bg{
    background: none no-repeat;
    width: 700px;
    height: 400px;
    margin:0 auto;
    background-size: cover; 
    position: relative;
    margin-bottom: 20px;
}

.onimg{
    position: absolute;
    top: 70px;
    left:50%;
    width: 600px;
    margin-left: -300px;
    text-align: center;
}
/*伪元素实现*/
.onimg_title:before{
    display: inline-block;
    position: relative;
    top:-7px;
    right: 20px;
    content: "";
    width: 200px;
    height: 0px;
    border: 2px solid #fff;
}
.onimg_title:after{
    display: inline-block;
    position: relative;
    top:-7px;
    left: 20px;
    content: "";
    width: 200px;
    color: #fff;
    height: 0px;
    border: 2px solid #fff;
}

复制代码

伪元素这种方法,也很简单,刚遇到的时候也是纠结了一下子,有时候是思路的问题,想到这个方法,问题就迎刃而解了。

代码解析:

须要注意的是使用伪元素content属性必不可少,而后给伪元素块级化,就能够像设置正常的元素同样设置你想要的样式了,在这里设置了一个没有高度,宽200px的长条,经过border控制高;

也能够经过设置背景图片background: none no-repeat,代替border实现

针对这种需求,目前只想到伪元素实现,若是您有更好的方法,欢迎留言。

相关文章
相关标签/搜索