This pen explain how to use a svg
A Pen by Jimmy Moon on CodePen.
<body> | |
<svg style="display:none"> | |
<defs> | |
<g id="svg-icon-def"><path d="M3,18h18v-2H3V18z M3,13h18v-2H3V13z M3,6v2h18V6H3z"/></g> | |
</defs> | |
</svg> | |
<!-- using img tag --> | |
<section> | |
<span>icon button with img tag</span> | |
<button> | |
<img src="https://cdn.mediacru.sh/4vbzA1qL3OsA.svg"> | |
</button> | |
</section> | |
<!-- xlink:href --> | |
<section> | |
<span>icon button with xlink:href</span> | |
<button> | |
<svg width="40" height="40" viewBox="0 0 40 40"> | |
<use xlink:href="#svg-icon-def"/> | |
</svg> | |
</button> | |
</section> | |
<!-- external svg with css --> | |
<section> | |
<span>icon button with css and svg file</span> | |
<button class="svg-icon-afile" role="img"></button> | |
</section> | |
<!-- data value --> | |
<section> | |
<span>icon buttons with data(base64)</span> | |
<button class="svg-icon-data" role="img"></button> | |
</section> | |
<!-- post insertion --> | |
<section> | |
<span>icon buttons with post insertion</span> | |
<button id="svg-icon-code"></button> | |
</section> | |
</body> | |
</html> |
function addSvgIcon (target, svgid, attrs) { | |
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); | |
var use = document.createElementNS('http://www.w3.org/2000/svg', 'use'); | |
attrs = attrs || {}; | |
for (var attr in attrs) { | |
use.setAttribute(attr, attrs[attr]); | |
} | |
use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', svgid); | |
svg.appendChild(use); | |
target.appendChild(svg); | |
} | |
document.addEventListener('DOMContentLoaded', function() { | |
var button = document.getElementById('svg-icon-code'); | |
addSvgIcon(button, '#svg-icon-def', {'x': 0, 'y': 0}); | |
}); |
.svg-icon-afile { | |
background-image: url(https://cdn.mediacru.sh/4vbzA1qL3OsA.svg); | |
background-position: 6px 6px; | |
} | |
.svg-icon-data { | |
background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBzdGFuZGFsb25lPSJubyI/Pgo8IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iIAogICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPgo8c3ZnIHZlcnNpb249IjEuMSIKICAgICB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4KICA8ZGVzYz5tZW51PC9kZXNjPgogIDxnIGlkPSJtZW51Ij48cGF0aCBkPSJNMywxOGgxOHYtMkgzVjE4eiBNMywxM2gxOHYtMkgzVjEzeiBNMyw2djJoMThWNkgzeiIvPjwvZz4KPC9zdmc+Cgo=); | |
background-position: 6px 6px; | |
} | |
button { | |
width: 40px; | |
height: 40px; | |
background-color: #fff; | |
padding: 6px; | |
cursor: pointer; | |
display: inline-block; | |
vertical-align: top; | |
} | |
button:focus { | |
outline: none; | |
} | |
button img { | |
width: 40px; | |
height: 40px; | |
display: block; | |
} | |
span { | |
line-height:40px; | |
} | |
section { | |
margin-bottom: 10px; | |
} | |
svg { | |
width: 40px; | |
height: 40px; | |
} |
This pen explain how to use a svg
A Pen by Jimmy Moon on CodePen.