Solid background behind text in multi-line p element

可紊 提交于 2019-12-06 02:53:05
gabssnake

Update: Chris Coyier did a roundup of techniques, posted 3 months after this answer. Notably, there is box-decoration-break which is now supported in Firefox 32 (released 02-09-2014) :

Modern solution. Webkit, Firefox 32+, IE11+ :

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

Demo at : http://jsfiddle.net/cLh0onv3/

To support IE9+, Webkit, Firefox, use box-shadow :

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

Demo : http://jsfiddle.net/cLh0onv3/1/

Old box-shadow method below:

p {
    display: inline;
    background-color: #FFAA3B;
    box-shadow: 1em 0 0 0 #FFAA3B, -1em 0 0 0 #FFAA3B;
    position: relative;
    left: 1em;
}

Demo at: http://jsfiddle.net/5xMkm/2/ - I first heard of this from @martijndevalk, so kudos to him. @gabitzish also showed this back in 2012.

Note : The box-shadow trick stopped working properly in IE11 and FF34. You can add box-decoration-break: clone; to make it work, or see update above.

jesse

Might be a bit late but. This will mean you don't need a <p> tag to define each line of text

http://jsfiddle.net/n6UYE/4/

check this fiddle.

This is not the only way but you can do this by assigning different p tags to each line and giving same class name to them.

HTML

 <div><p>Lorem ipsum dolor sit amet, consectetur</p><br>
 <p>adipiscing elit. Duis nec purus tellus, quis pulvinar</p><br>
 <p>tortor. Sed mattis lobortis gravida. Lorem ipsum</p><br>
 <p>dolor sit amet.</p></div>​

CSS

 p
{
  background-color:rgba(255,165,0,0.2);
  padding:0 15px 0 15px;   
  display:inline;
  border-radius:15px;
  text-shadow:0px 0px 0px rgba(255, 210, 82, 1);
}
div{margin:15px;}
tibalt

I wouldn't suggest to use box-shadow for that, cause it works with glitches in IE:

I've posted the solution with 'box-decoration-break: clone' for webkit/firefox and 'white-space: pre-wrap' for ie here:

https://stackoverflow.com/a/26677158/337549

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!