Inline SVG alignment in HTML

2019-03-30 16:48发布

I currently have problems aligning inline SVG correctly inside a bounding DIV, like in this example.

<!DOCTYPE html>
<html>
<body>
    <div style="border: 1px solid black; height: 50px; width: 100px; vertical-align:top;">
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"">
            <rect x="0" y="0" width="100" height="100" style="fill: red;" />
        </svg>
    </div>
</body>
</html>

The SVG gets resized to match the the dimensions of the div, but I am not able to set any alignment for the SVG. Neither text-align nor vertical-align seem to work in Firefox 9, Chrome 18, IE 9 or Opera 11.61 . I just want to position the inline SVG at the upper left corner of the DIV.

Note that in my case the surrounding DIV has dynamic dimmension (%-values), so using absolute positioning does not work.

Anybody have any clue how to align the SVG in this case?

2条回答
太酷不给撩
2楼-- · 2019-03-30 17:47

Add preserveAspectRatio="xMinYMin" as an attribute on the svg element e.g. http://jsfiddle.net/longsonr/fLWhu/

查看更多
倾城 Initia
3楼-- · 2019-03-30 17:47

Add preserveAspectRatio="xMidYMid meet" attribute to <svg> element as per http://tutorials.jenkov.com/svg/svg-viewport-view-box.html.

查看更多
登录 后发表回答