在html元素/标记后的偏移背景

时间:2016-02-19 12:35:56

标签: html css

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

以下是我正在寻找的结果:

enter image description here

您可以看到指向红色箭头的轻微背景,该背景在<h2>文本之前开始,在文本结束之前结束。此背景应随着元素中的文本量而扩展。

我尝试使用框阴影进行此操作,您可以在下面看到:

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

但是你可以看到背景没有出现在文本背后。

让我知道是否有人做过这样的事情:)

3 个答案:

答案 0 :(得分:6)

伪元素在这里是理想的:

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>

答案 1 :(得分:4)

试试这个:

&#13;
&#13;
<h2>Ain't No Mountain</h2>
&#13;
fgets
&#13;
&#13;
&#13;

这将创建一个位于h2元素后面的框。

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

答案 2 :(得分:2)

可能不是最干净的解决方案但是:

<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