Reputation: 1471
I have a simple svg
hamburger menu like this:
<svg viewBox="0 0 100 100" width="25" height="25">
<symbol id="bar">
<title>Bar</title>
<desc>Bar for forming hamburger menu button</desc>
<rect width="100" height="10"></rect>
</symbol>
<g id="hamburger" transform="translate(0, 0)">
<use y="0" xlink:href="#bar" />
<use y="20" xlink:href="#bar" />
<use y="40" xlink:href="#bar" />
</g>
</svg>
Now if I want to center it, I can use translate
to do the job, but I have to calculate based on the size of the svg that will be rendered in html (i.e 25px
, as shown in width
and height
).
Is it possible to center it without considering HTML? Is there any no-brainer equivalent in SVG to the following in CSS?
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Upvotes: 0
Views: 698
Reputation: 101800
SVG elements do automatic centering by default anyway. So all you need to do is set the width of the SVG to be the whatever you wish. For example, in the snippet below I've set it to be the same as its parent (width: 100%
).
.parent {
width: 300px;
background: linen;
}
.parent svg {
width: 100%;
}
<div class="parent">
<svg viewBox="0 0 100 100" width="25" height="25">
<symbol id="bar">
<title>Bar</title>
<desc>Bar for forming hamburger menu button</desc>
<rect width="100" height="10"></rect>
</symbol>
<g id="hamburger" transform="translate(0, 0)">
<use y="0" xlink:href="#bar" />
<use y="20" xlink:href="#bar" />
<use y="40" xlink:href="#bar" />
</g>
</svg>
</div>
Upvotes: 1
Reputation: 13070
I would go with Flexbox. Here just placing the SVG in a parent element that is displayed as flex and then justify-content: center
.
.parent {
display: flex;
justify-content: center;
background-color: silver;
width: 200px;
}
<div class="parent">
<svg viewBox="0 0 100 100" width="25" height="25">
<symbol id="bar">
<title>Bar</title>
<desc>Bar for forming hamburger menu button</desc>
<rect width="100" height="10"></rect>
</symbol>
<g id="hamburger" transform="translate(0, 0)">
<use y="0" xlink:href="#bar" />
<use y="20" xlink:href="#bar" />
<use y="40" xlink:href="#bar" />
</g>
</svg>
</div>
Upvotes: 0