The solution for adding horizontal lines on both sides of the text

 

(non-original)

 

Let's look at the first one, the implementation of the background solid color.

One way to do this is to use an empty label to write the line. Of course, you can also use the background image to cut a picture with a transparent middle and white bars on both sides. Pseudo-elements can also be used. before after before and after the attack.

When the background is a picture, the pseudo-element method is used. Personally, I feel that the pseudo-element is really too powerful.

Without further ado, the code:

HTML:

<div class="onpure_bg">

<h2 class="onpure">

<span class="onpure_title">Title goes here</span>

</h2>

<span class="line"></span>

</div>

CSS:

/*Pure background implementation principle code*/

.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 {

/*Key point: Set the same color as the background color. */

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;

}

Code analysis:

把标题和线条定位左右居中,上下靠上部分,用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实现

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326280766&siteId=291194637