Svg Foreignobject Not Working Properly on Safari

Safari foreignObject getBBox is wrong

Wrap the foreignObject in a <g> and get the bounding box of the wrapper.

console.log(document.querySelector('.foreignObjectWrapper').getBBox());console.log(document.querySelector('#rect').getBBox());
<!DOCTYPE html><html><head>  <meta charset="utf-8">  <meta name="viewport" content="width=device-width">  <title>JS Bin</title></head><body>   <svg viewBox="0 0 200 200" style="height: 200px; width: 200px;" xmlns="http://www.w3.org/2000/svg">    <rect width="100%" height="100%" fill="red"/>    <rect id="rect" x="50" y="50" width="100" height="100" fill="green"/>     <g class="foreignObjectWrapper">    <foreignObject x="50" y="50" width="100" height="100">      <div style="background-color: yellow; width: 100px; height:100px;">      </div>    </foreignObject>     </g>  </svg></body></html>

SVG foreignObject behaves as though absolutely positioned in Webkit browsers

This issue is not specific to Chrome as I could reproduce it in Chrome 15.0.874.121 for Macintosh as well as Safari 5.1.2. (It also occurred in older versions of Firefox for Mac, such as version 3.6.8, but the behavior is correct in the current version.) This currently outstanding Webkit bug is likely to be the cause of the issue. Global coordinates are incorrectly used for elements inside the foreignObject which means when absolute positioning is used, those elements are placed relative to the main document flow rather than the foreignObject container, and thus the SVG translate is not applied to those elements.

I have not been able to locate a general solution to this issue.

For this specific example, this will fix the layout in all of the above-mentioned browsers:

.widget {
position: relative;
left: 100px;
top: 200px;
}

Demonstration on jsfiddle.



Related Topics



Leave a reply



Submit