Search code examples
htmlcsssvgbuttoncentering

How do I perfectly center a square SVG within a square button?


NOTE: this question was closed as a duplicate of this question about centering text within a div block. My question is about centering an SVG within a button. Buttons apparently have a lot of hidden properties that make this much more difficult than centering inside a simple div.

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>


Solution

  • Set the SVG to display block and then replace the widht and the height on the button with a margin in the SVG.

    #search-button {
      padding: 0;
      margin: 0;
    }
    
    #search-button-svg {
      outline: 1px dotted red;
      width: 2em;
      height: 2em;
      display: block;
      margin: calc(.5em - 2px); /* subtract the width of the border of the button */
    }
    <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>