Search code examples
svgwidthinternet-explorer-11

IE11 defaults SVG to 100% width - how to refactor this code?


I am not aware of alternatives to adding width: 1em to the SVG in order to fix the IE11 issue (please see comment in the code). Play with the code in the codepen. Appreciate any help! Thanks :)

https://codepen.io/ambrwlsn90/pen/zjZYpb

<div class="box">
    <span class="handle--draggable">
      <svg class="handle--icon" xmlns="http://www.w3.org/2000/svg" 
viewBox="0 0 10 32">
        <circle cx="2" cy="2" r="2" />
        <circle cx="8" cy="2" r="2" />
        <circle cx="2" cy="9" r="2" />
        <circle cx="8" cy="9" r="2" />
        <circle cx="2" cy="16" r="2" />
        <circle cx="8" cy="16" r="2" />
        <circle cx="2" cy="23" r="2" />
        <circle cx="8" cy="23" r="2" />
        <circle cx="2" cy="30" r="2" />
        <circle cx="8" cy="30" r="2" />
      </svg>
    </span>
</div>

.box {
  position: relative;
  width: 400px;
  height: 100px;
  border: 3px solid black;
  background-color: white;
  top: 50px;
  left: 100px;
  padding: 15px;
  line-height: 1.5em;
}

.handle--draggable {
  position: absolute;
  cursor: move;
  left: -26px;
  top: -3.5px;
}

/**
  * 1. Magic number added to fix visual bug in IE: 11
  */

.handle--icon {
  fill: black;
  background-color: grey;
  padding: 3.5px;
  height: 37px;
  width: 1em; /* 1. */
  position: relative;

  &:hover {
    left: -5px;
    border-right: 5px solid grey;
  }
}

Solution

  • The SVG tag needs some basic attributes in order to be rendered as expected. If you read the W3C documentation according the outermost svg tag you will find the answer:

    For embedded ‘svg’ elements, the width of the rectangular region into which the ‘svg’ element is placed. A negative value is an error (see Error processing). A value of zero disables rendering of the element. If the attribute is not specified, the effect is as if a value of '100%' were specified.

    So you will need to specify the width and height attributes of the SVG tag, or it will be rendered at 100% width.

    The opening svg tag should look like this:

    <svg class="handle--icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 32" width=“10” height=“32”>
    

    Then the SVG will look the same crossbrowser.

    Having the width and height attributes defined on your svg element you can discard the ugly Internet Explorer 11 hack.