I tried using this solution to help me center a square SVG within a square button (horizontally and vertically, of course). The main differences is that, in the solution, the coordinate system of the SVG viewBox is different (but still square). Also, I specify a width and height for the button (still square, though). The solution demonstrated that styling the search-button with padding: 0
fixed the problem.
For me, though, the SVG is clearly nearer the top than the bottom, as the red outline shows. (It also may be nearer the left than the right, but that could be an optical illusion.)
I’ve tried to eliminate all non-essential styling from this example. What is needed to coerce the SVG to be perfectly centered inside the button?
#search-button {
align-items: center;
width: 3em;
height: 3em;
padding: 0; /* one solution used this */
}
#search-button-svg {
outline: 1px dotted red;
width: 2em;
height: 2em;
}
<button type="submit" id="search-button">
<svg id="search-button-svg"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 512 512">
<path d="M416 208c0 45.9-14.9 88.3-40
122.7L502.6 457.4c12.5 12.5 12.5 32.8 0
45.3s-32.8 12.5-45.3
0L330.7 376c-34.4 25.2-76.8 40-122.7
40C93.1 416 0 322.9 0
208S93.1 0 208 0S416 93.1 416 208zM208
352a144 144 0 1 0
0-288 144 144 0 1 0 0 288z"/>
</svg>
</button>
3
Answers
I could not get the suggested flex to work, and note that your align-items has no effect in the code you have given.
Instead this snippet resorts to the old fashioned positioning with translate, setting the svg to position: absolute so it has no effect on the button.
Make sure the
line-height
within the button is also zero.Set the SVG to display block and then replace the widht and the height on the button with a margin in the SVG.