Categories
CSS

Remove unwanted spacing on repeated SVG background in webkit browser

If you have SVG used as CSS background and the background has fixed background-size defined using percentage so you can rendered it repeatedly for n time, the chance is you’ll have this unwanted spacing issue in webkit browser.

For example you have this wrapper:

<div class="wrapper"></div>

Then you have this CSS:

.wrapper {
  display: inline-block;
  width: 600px;
  height: 200px;
  background: red;

  /* repeat the image 7 times horizontally */  
  background-size:14.285714286% 70px; 

  /*Free Chevron Pattern SVG provided by SVGeez.com - CC 4.0 License - © 2019 Megan Young */
  background-image:url("data:image/svg+xml;charset=utf8,%3Csvg id='Layer_1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 500 500' fill-opacity='1' style='enable-background:new 0 0 500 500'%3E%3Cstyle%3E .st1{fill:rgb(82, 230, 227)} %3C/style%3E%3Cpath style='fill:none;stroke:rgba(255,255,255,1);stroke-width:50;stroke-miterlimit:10' d='M-44-184l83 92 83-92 83 92 83-92 83 92 83-92 83 92 83-92'/%3E%3Cpath class='st1' d='M.8 500L-101 387.4l37.2-33.5L.8 425.4l83.1-92 83.2 92 83.2-92 83.1 92 83.2-92 83.2 92 64.6-71.5 37.2 33.5L499.8 500l-83.2-92-83.2 92-83.1-92-83.2 92-83.2-92zM.8 333.3L-101 220.7l37.2-33.4L.8 258.7l83.1-92 83.2 92 83.2-92 83.1 92 83.2-92 83.2 92 64.6-71.4 37.2 33.4-101.8 112.6-83.2-92-83.2 92-83.1-92-83.2 92-83.2-92zM.8 166.6L-101 54.1l37.2-33.5L.8 92 83.9 0l83.2 92 83.2-92 83.1 92 83.2-92 83.2 92 64.6-71.4 37.2 33.5-101.8 112.5-83.2-92-83.2 92-83.1-92-83.2 92-83.2-92z'/%3E%3C/svg%3E");  
}

You’ll have this unwanted spacing happens:

Unwanted spacing on repeated svg background

This happened because the percentage background size when being calculated against the wrapper produces decimal number and webkit renders it as this unwanted spacing:

defined horizontal background size: 14.285714286% 

element width: 600px

calculated background size: (600 / 100) * 14.285714286
calculated background size: 85.714285716px

The .714285716px is what’s causing the unwanted spacing. I’ve tried all the CSS tricks that i can possibly think of but couldn’t fix it. The only feasible way to do this that i can find, is to use JS to translate the percentage based value into integer and px based value then insert it as inline style. I’ve put together a codepen for it:

Remember: if the wrapper dimension has fluid width (ie: responsive style on other breakpoint) after doing this, you’ll need to listen to resize event and adjust this value accordingly when the window dimension is changed.

Leave a Reply

Your email address will not be published. Required fields are marked *