CSS:多行文字的背景色?

时间:2012-10-03 13:16:13

标签: css

您是否有想在多行文字上添加“背景颜色”属性,但有两个难点:

  • 背景必须在每行的最后一个单词后停止
  • 没有背景的每一行之间没有空格

示例:

enter image description here

谢谢!

7 个答案:

答案 0 :(得分:12)

我认为这正是您所寻找的:http://jsfiddle.net/9BTYQ/1/



span {
    color: white;
    background-color: #343132;
    box-shadow: 0.5em 0 0 #343132,-0.5em 0 0 #343132;
}

div {
    width: 100px;
}

<div>
    <span>Do you have an idea to add a background-color property on a multi-line text, with two difficulties:</span>
</div>   
&#13;
&#13;
&#13;

答案 1 :(得分:5)

@gabitzish所示的box-shadow解决方案在IE11和FF34 +(2014年9月发布)中停止正常工作。

您可以添加box-decoration-break:clone;以使其在IE11和FF34 +中运行:

p {
    display: inline;
    padding: 0.5em 0em;
    background-color: #FFAA3B;
    box-shadow: 1em 0 0 #FFAA3B, -1em 0 0 #FFAA3B;
    box-decoration-break: clone;
}

适用于Webkit,Firefox,IE9 +,并带有正确的前缀。

演示:http://jsfiddle.net/cLh0onv3/1/

注意:已经说明了elsewhere

答案 2 :(得分:3)

我发现这个解决方案可以很好地结合使用box-shadow方法和<p>元素周围<span>元素上的一些相应填充

p {
  display:block;
  padding:0 10px;
  font-size:2em;
}

span {
  color: white;
  background:#333;
  box-shadow: 0 0 0 10px #222;
  padding:0;
  line-height:1.5;
}

http://jsfiddle.net/tsoligo/mMg4B/

答案 3 :(得分:1)

使用纯CSS实现完美是很困难的,只有在某些条件下才能实现。例如,如果您使用中断并将line-height设置为big,则会在两者之间看到间隙。那边两边的衬垫怎么样?

另外,你需要跨度,这只会使你的标记变得丑陋。

幸运的是,Sam Croft提出了一个简单的jQuery插件来对付这个问题。它快速,轻便,适用于大多数情况。

文章:http://samcroft.co.uk/2011/jquery-plugin-for-inline-text-backgrounds/

演示:http://samcroft.co.uk/demos/inline-backgrounds/

来源:https://github.com/samcroft/css-inline-backgrounds/blob/master/inline-backgrounds.js

答案 4 :(得分:1)

只需将显示框类型更改为内联:

p {
  display: inline;
}

body {
  width: 170px;
}
p {
  display: inline;
  background: black;
  color: white;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

如果每行之间有空格,则将font-size设为line-height或v.v。

答案 5 :(得分:0)

这是<span><p>标记之间的区别之一。

<span style="background:black; color:white;">
Lorem Ipsum is simply dummy text of the<br>
printing and typesetting industry.<br>
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
<br> when an unknown printer took a galley of type
<br> and scrambled it to make a type specimen book.</span>

答案 6 :(得分:0)

box-shadow示例效果很好:

HTML

<p class="title step-1">
    <span class="highlight">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit, qui suscipit error quasi tempore magni sit nostrum aliquam soluta vel. Dolorem, reprehenderit sint molestiae in est perspiciatis quas accusantium commodi. </span>
</p>

CSS

.title {
  font: 20px/1.25 Ubuntu, sans-serif;
  text-transform: uppercase;
  margin-bottom: 1rem;
  line-height: 45px;
  display: inline-block;
  width: 300px;
}
.title .highlight {
  display: inline;
  background: #ee4035;
  color: white;
  padding: 0.5rem;
  padding-left: 0;
  padding-right: 0;
}
.title.step-1 .highlight {
  box-shadow: 10px 0 0 #ee4035, -10px 0 0 #ee4035;
}

JSFiddle: http://jsfiddle.net/verber/WmRT3/

P.S。但不是在IE8中......

相关问题