I have this piece of html:
<svg >
<use href="icon.svg#icon"></use>
</svg>
And I need to center <use>
tag in <svg>
tag. <svg>
tag has size of 20 by 20 pixels, while svg file in <use>
tag has only 13 by 10 pixels size.
Approaches with
position:absolute;
top:50%;
bottom:50%;
transform:translate(-50%, -50%);
and
display: flex;
align-items: center; /* vertical alignment */
justify-content: center;
for <use>
tag are not working for me
update:
I kinda figured it out, but I can't get why it works that way.
When I set width
and height
properties for <svg>
tag, <use>
tag moves from the center to the top left of <svg>
element
CodePudding user response:
You must stablish width property to USE tag, also I think you are overthinking the center property in SVG tag.
Read this article for a very simple use of Flex in css
CodePudding user response:
Wrap your icon in a <symbol>
and add suitable viewBox
attribute (e.g . viewBox="0 0 13 10").
Your <use>
instance will be centered within the parent <svg>
element.
<svg style="border:1px solid red; height:200px" viewBox="0 0 200 100">
<use href="#home" />
</svg>
<svg style="border:1px solid red; height:200px; width:200px">
<use href="#home" />
</svg>
<svg style="border:1px solid red; height:200px" viewBox="0 0 10 40">
<use href="#home" />
</svg>
<!-- hidden svg asset to emulate external icon reference -->
<svg style="width:0; height:0;">
<symbol id="home" viewBox="0 0 34 48">
<path d="M33.16,28.12h-5.2v13h-3.44v-16.72l-7.72-8.72l-7.72,8.72v16.72h-3.44v-13h-5.24l16.4-17.4Z" />
</symbol>
</svg>