2016-02-19 35 views
0

我想在任何HTML元素或标记后面设置CSS背景,它应该有点偏移。html元素/标记背后的偏移背景

下面是我在寻找的结果:

enter image description here

你可以看到尖锐的红色箭头,其是<h2>文本之前开始和文本结束前结束了轻微的背景。这个背景应该随着元素中文本的数量而扩展。

我试图与框的阴影这样做,你可以看到如下:

body { 
 
    padding: 20px; 
 
} 
 
h2 { 
 
    display: inline-block; 
 
    box-shadow: -10px 10px 0 red; 
 
}
<h2>Ain't No Mountain</h2>

但你可以看到背景没有出现后面的文字。

让我知道,如果有人做了这样的事情:)

回答

7

伪元素是这里的理想:

body { 
 
    padding: 20px; 
 
} 
 
h2 { 
 
    display: inline-block; 
 
    position: relative; 
 
} 
 
h2::before { 
 
    content: ""; 
 
    position: absolute; 
 
    width: 100%; 
 
    height: 100%; 
 
    top: 5px; 
 
    left: -5px; 
 
    background: rgba(255, 0, 0, 0.25); 
 
    z-index: -1; 
 
}
<h2>Ain't No Mountain</h2>

+0

为什么在'h2 :: before'中使用双冒号? – Omer

+1

因为双冒号是当前的方法。 - http://stackoverflow.com/questions/17684797/should-i-use-single-colons-or-double-colons-for-before-after-first-le –

5

试试这个:

h2 { 
 
    position:relative; 
 
    z-index:1; 
 
} 
 
h2:after { 
 
    content:""; 
 
    position:absolute; 
 
    width:80%; 
 
    height:100%; 
 
    background-color:rgba(0, 0, 0, .1); 
 
    left:-10px; 
 
    bottom:-10px; 
 
    z-index:-1; 
 
}
<h2>Ain't No Mountain</h2>

这将创建一个盒子是H2-元素后面。

如果我是你,我会给h2-element添加一个类,这样你就可以决定哪些元素应该有这种效果。

+0

威尔这也适用于文本将会扩展的时候,或者我向t添加更多的文本帽子元素? – Omer

+0

是的,但我会将高度更改为100%以匹配h2文本的高度。另外h2:之后需要z-index:-1;正确地出现在h2元素的后面。看到这里:http://jsbin.com/boyixupalo/edit?html,css,output – Joseph

+0

我已经改变了高度为100%,在我的答案,如约瑟夫说。 the:after不需要z-index:-1 ;,正如我给出的h2 z-index:2; – rblarsen

3

也许不干净的解决方案,但是:

<div style="display: inline-block;background-color: red;"> 
    <span style="position: relative;top: -10px;left: 20px;"> 
     Ain't No Mountain 
    </span> 
</div> 

明显ussig css文件,请; d