How can I stop the transparent background of multiline text overlapping between lines?

爱⌒轻易说出口 提交于 2019-12-10 18:09:07

问题


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

  1. The background color must conform to the shape of the text; so setting the span to display:inline-block is not a workable solution.
  2. Setting a fixed line-height (or padding) is not an optimal answer as the exact font rendering changes between browsers, and user's settings. Setting the line-height perfectly in Chrome will product an imperfect result in Firefox, for example.
  3. The text must be dynamic and semantic. A solution cannot involve rendering an image representation of the text on the server for the client.
  4. 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.
  5. 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

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