问题
I have to add a background-color to a text (a title for example) adding some padding around it.
Applying display:inline-block padding is perfect, but obviously, background will span across entire block width (e.g. 100%).
Design requires to have a separate background strip for each line of text, and this could be achieved using display:inline with a line-height:160%; but this has the drawback of applying padding left only on first row and padding right only on the last.
Here a jsFiddle with two examples. The second one is the most similar to desired behaviour but obviously padding is not correct.
Relevant part of CSS code is:
.inline-block
{
display:inline-block;
padding:5px 20px;
}
.inline
{
display:inline;
padding:5px 20px;
line-height:160%;
}
How to combine advantages of two approaches?
回答1:
You can utilize the box-shadow CSS call for this purpose. I have completed a fiddle with end result. You can then play around with it to get the exact result you want
CSS:
.highlightme {
background-color: #A8332E;
padding: 0.5rem 0;
-webkit-box-shadow: 1rem 0px 0px #A8332E, -1rem 0px 0px #A8332E;
box-shadow: 1rem 0px 0px #A8332E, -1rem 0px 0px #A8332E;
box-decoration-break: clone;
}
JSFiddle
回答2:
Taking inspiration by other answers that suggested use of box-decoration:break; property, I investigated on this topic, finding also this page with some possible solutions.
The best that "actually" (browser support varied during time) is to combine the cited "Fabien Doiron's box-shadow Method" with a little modification to address only specific behaviour of Firefox 32+.
The updated jsFiddle has the following specific rule:
.inline
{
display:inline;
padding:5px 20px;
background:blue;
color:white;
line-height:160%;
box-shadow: 10px 0 0 blue, -10px 0 0 blue;
box-decoration-break: clone;
}
Multiple box-shadow is used in all browsers to mimic lateral padding, while is necessary to add box-decoration-break: clone; to override specific Firefox 32+ behaviour that has box-decoration-break: split; as default.
NOTE about cross-compatiblity:
box-decoration-break: clone; is necessary only for FireFox.
Rather in Chrome, is (actually) mandatory to NOT set equivalent -webkit-box-decoration-break: clone; because it adds an unwanted horizontal overflow on window resize. So, due to fact that Chrome needs vendor prefix fro this property, declaring it only with standard syntax is a workaround to make it running correctly even in it and also in IE9+
来源:https://stackoverflow.com/questions/33096660/text-with-background-color-separated-for-each-row