skip to Main Content

I have an SVG line (simplified for this example), that should be 100% of the container width, I tried to use two methods to insert an SVG image into my page, but I faced a problem in Safari and Firefox browsers, that SVG doesn’t work correctly with the img tag, it left some space on the left and right side.

How can I fix that?

Interactive example: https://codepen.io/mxddx/pen/zYVWdGz

Some space on the left and right side at second line

.wrapper {
  width: 100%;
  padding: 2px 0px;
  background: #090;
}

.svg {
  width: 100%;
}

img {
  width: 100%;
}
<div class="wrapper">
  <svg class="svg" viewBox="0 0 1380 6" fill="none" xmlns="http://www.w3.org/2000/svg">
    <rect width="1380" height="6" rx="4" fill="black"/>
  </svg>
</div>
<hr/>
<div class="wrapper">
  <img src="https://svgshare.com/i/19We.svg" />
</div>
<hr/>
<div class="wrapper">
  <!-- No viewBox -->
  <img src="https://svgshare.com/i/19XH.svg" />
</div>

I tried to add viewBox, width, and height in different combinations but it’s not help

2

Answers


  1. I tested it on firefox and safari.

        .wrapper{
          padding: 2px 0px;
          background: #090;
          height: 30px;
        }
        .svg{
          width: 100%;
        }
        .wrapper2{
          position: relative;
          padding: 2px 0px;
          background: #090;
          height: 30px;
        }
        img{
          width:100%;
          height:100%;
          position: absolute;
          inset: 0;
        }
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
      <div class="wrapper">
        <!-- work as aspected in Chrome, Safari, Firefox -->
        <svg class="svg" viewBox="0 0 1380 6" fill="none" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none">
          <rect width="1380" height="6" rx="4" fill="black"/>
        </svg>
      </div>
      <hr/>
      <div class="wrapper2">
        <!-- work as aspected in Chrome. Work wrong Safari, Firefox !!! -->
        <img src="https://svgshare.com/i/19We.svg"/>
      </div>
    </body>
    </html>
    Login or Signup to reply.
  2. I can see it happen in both FireFox and Chrome when zooming in/out the page.
    In OPs Code Snippet (full page mode), FireFox adds more padding than Chrome:

    Is your browser page at 100% ?? press Ctrl-0

    maybe working with percentages helps

    <svg class="svg" viewBox="0 0 1380 6" fill="none" xmlns="http://www.w3.org/2000/svg">
      <rect width="100%" height="100%" rx="4" fill="black"/>
    </svg>
    

    The width of an open Console also affects it

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search