6

Is it possible to edit the height of the background color in my span?

HTML

<span class="highlight">Some highlighted text</span>

CSS

  .highlight{
font-family: 'Roboto', sans-serif;
    font-weight: 300;
    font-size: 1.5em;
        background-color: #4db6ac;
        line-height: 2em;
    }

What I want to do is for the highlight to be 1.8em. I'm not sure how to implement this without it being too tedious (ie. lots of divs ).

Acrux
  • 338
  • 3
  • 23

4 Answers4

6

If anyone is looking for an answer as to how to expand the background color of a <span> elements text to be taller than the text itself, but still want the <span> to be inline, then none of these other solutions will work, since the background color is not affected by the line-height or height of a span. It's only affected by the font-size and padding. Here would be a proper solution for that case:

body { 
    font-size: 1em; 
    line-height: 1.5em; 
}
span.highlight {
    background: yellow;
    padding: 0.25em 0; /* ('line-height' - 'font-size') / 2 */
}
span.no-padding { 
    padding: initial; 
}
<p style="width:400px">
  Here is a bunch of text that will have some highlighted text within it.
  <span class="highlight">
    Here is some highlighted text that will span multiple lines and will have a full height background color.
  </span> 
</p>
<p style="width:400px">
  Here is also some highlight text without the padding. 
  <span class="highlight no-padding">
    Here is some highlighted text without a full height background, regardless of having the same 'line-height'
  </span>
</p>
corylulu
  • 3,369
  • 1
  • 17
  • 34
4

You can use a vertical linear-gradient with transparent top and bottom color (I've used red in the example).

The height of the element is 2em because of the line-height, so 1.8em is 90%. Create a gradient with two transparent strips (red in the demo) of height 5% each. The rest of the 90% will be the highlight color.

.highlight {
  font-family: 'Roboto', sans-serif;
  font-weight: 300;
  font-size: 1.5em;
  background: linear-gradient(to bottom, red 5%, #4db6ac 5%, #4db6ac 95%, red 95%);
  line-height: 2em;
}
<span class="highlight">Some highlighted text</span>
Ori Drori
  • 166,183
  • 27
  • 198
  • 186
2

By setting display property to inline-block your background size will become equal to line height without adding any div. Hope this works for you!

 .highlight{
    display:inline-block;
    font-family: 'Roboto', sans-serif;
    font-weight: 300;
    font-size: 1.5em;
    background-color: #4db6ac;
    line-height: 2em;
  }
Pooja Jain
  • 46
  • 3
0

Add display property as inline-block, your background size will become equal to line height without adding any div. this will works for you!

.highlight{
display:inline-block;
font-family: 'Roboto', sans-serif;
font-weight: 300;
font-size: 1.5em;
background-color: #4db6ac;
line-height: 2em;

}

sudhanshum
  • 49
  • 2