Filling a simple SVG in a div

2019-07-24 00:30发布

Here is my relevant HML with SVG:

     <div style="width:24px;height:24px;margin:0px;padding:0px;background:black;">
        <svg   viewBox="0 0 24 24">
          <path fill="red" d="M24 12l-9-9v7h-15v4h15v7z"/>
        </svg>
     </div>

It renders fine but leaves padding above and below the arrow inside the div.

I tried using SVG as background to the div after base64 encoding the SVG tag, as in:

    <div style="width:24px; height:24px;margin:0px;padding:0px;background-image:url('data:image/svg+xml;base64,PHN2ZyBmaWxsPSJyZWQiIHRyYW5zZm9ybT0ic2NhbGUoMSwxKSIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBkPSJNMjQgMTJsLTktOXY3aC0xNXY0aDE1djd6Ii8+PC9zdmc+');">
     </div>

It displays nothing!

Yes there are similar questions asked but this is NOT a duplicate. Nothing in the answers posted to similar questions on SO resolve this problem.

标签: html css svg
2条回答
\"骚年 ilove
2楼-- · 2019-07-24 00:56

The fill needs to be on the path instead of the svg element.

Also, try adding the width="24" and height="24" to the svg element.

查看更多
Animai°情兽
3楼-- · 2019-07-24 01:13

I'm not very sure I understand your question. Maybe this is what you need:

I've changed the viewBox to viewBox="0 3 24 18". In order to get this value I've console.log(thePath.getBBox())

The method getBBox() returns an object with the position and the size of the bounding box of the path. I'm using this values for the new viewBox

viewBox = bb.x bb.y bb.width bb.height

Where bb is the bounding box.

<div style="width:24px;height:18px;margin:0px;padding:0px;background:black;">
        <svg viewBox="0 3 24 18">
          <path id="thePath" fill="red" d="M24 12l-9-9v7h-15v4h15v7z"/>
        </svg>
     </div>

查看更多
登录 后发表回答