Search code examples
htmlcsssvgmedia-queries

SVG height with em is not responsive


I need make responsive line-height and background-image depends of font-size value:

p {
  font-size: 30px;
  line-height: 1.93333333em;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' height='1.93333333em' width='400' viewBox='0 0 400 5' preserveAspectRatio='xMinYMax' %3e%3cline x1='0' y1='0' x2='100%' y2='0' style='stroke:rgb(255,0,0);stroke-width:5' /%3e%3c/svg%3e");
}

@media screen and (max-width: 500px) {
  p {
    font-size: 15px;
  }
}
<p>Hi people!<br>How are you?<br>I`m good!</p>

In this situation 1em = 30px, so 1.933333em = 58px. As you can see I set height of svg background-image too: height='1.93333333em'. I expected that height of background will be 58px, but actually it's 30px like 1em = 16px. If I set height='58px' for background-image I get what I want.

And if screen size is 500px, that line-height changes, but height of background-image not.

How does em work in SVGs and how can I make SVG size responsive?


Solution

  • This is how I would do it:

    The SVG has no width or height but I defined the viewBox='0 0 5 5'. For the size you can use the CSS background-size:1.93333333em; and let the image repeat on x and y.

    p {
      font-size: 30px;
      padding:0;
      line-height: 1.93333333em;
      background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 5 5' preserveAspectRatio='xMinYMax' %3e%3cline x1='0' y1='0' x2='100%' y2='0' style='stroke:rgb(255,0,0);' /%3e%3c/svg%3e");
      background-size:1.93333333em;
    }
    
    @media screen and (max-width: 500px) {
      p {
        font-size: 15px;
      }
    }
    <p>Hi people!<br>How are you?<br>I`m good!<br><br></p>

    Alternatively you can use CSS linear gradients instead of SVG for the background image.

    p {
      font-size: 30px;
      padding:0;
      line-height: 1.93333333em;
      background-image: linear-gradient(transparent 0%, transparent 1.93333333em, red 1.93333333em, transparent 2em, transparent 3.93333333em, red 3.93333333em, transparent 4em, transparent 5.93333333em ,red 5.93333333em, transparent 6em);
    
    }
    
    @media screen and (max-width: 500px) {
      p {
        font-size: 15px;
      }
    }
    <p>Hi people!<br>How are you?<br>I`m good!<br><br></p>