问题
I'm facing an issue where I have an inline <span>
containing multiline text, with a transparent background. Despite having a default line-height, the background on the text overlaps, causing darker, horizontal rows where the background is overlaid onto itself.
Here is a good demonstration of the problem (image + jsfiddle)
JsFiddle demonstrating this issue.
Minimal reproduction of issue
HTML:
<h1>
<span>Although it is set to a line height of 1, the background behind text still overlaps between rows.</span>
</h1>
CSS:
h1 {
text-transform: uppercase;
font-family: Arial;
line-height: 1;
font-size: 30px;
background: rgba(0,0,0,0.5);
color: #FFF;
display: inline;
}
h1 span {
position: relative;
}
Solution requirements
- The background color must conform to the shape of the text; so setting the
span
todisplay:inline-block
is not a workable solution. - Setting a fixed
line-height
(orpadding
) is not an optimal answer as the exact font rendering changes between browsers, and user's settings. Setting theline-height
perfectly in Chrome will product an imperfect result in Firefox, for example. - The text must be dynamic and semantic. A solution cannot involve rendering an image representation of the text on the server for the client.
- Preferably allows for arbitrary
padding
to be added or removed to reduce or increase the space between the text and the edge of the background. - Javascript could be fine. I'm using Angular 2 here, so answers which integrate nicely with that are even better.
回答1:
Line height will accept a 'none' value, so you can set that and it works (if it's display:block), however (at least in chrome, safari and ff on Mac) anything inline had a 1px gap between the lines. So in the solution below I just added a padding top of 1px to the span to adjust for that gap. I'ts a little hacky, but it gets the job done. You'll want to do much more browser testing obviously. It scales fairly well with browser zoom on chrome and ff, but gets a little off at really large zoom rates on safari.
h1 {
text-transform: uppercase;
font-family: Arial;
line-height: none;
font-size: 30px;
color: #FFF;
}
h1 span {
background: rgba(0,0,0,0.5);
line-height: inherit;
display: inline;
padding-top: 1px;
}
<h1>
<span>Although it is set to a line height of 1, the background behind text still overlaps between rows.</span>
</h1>
来源:https://stackoverflow.com/questions/39238429/how-can-i-stop-the-transparent-background-of-multiline-text-overlapping-between