Home > Software design >  Centering SVG Icon inside a button
Centering SVG Icon inside a button

Time:01-12

I have <div>s that are functioning as buttons, but I'm trying to replace them with actual <button>s, for accessibility and to allow the tab key to focus on my buttons. Each button contains a centered SVG image. But when I traded out my tags, the images became off-center. (They also became gray, but that was easy to fix with the style background-color:transparent;.)

Does anybody know why these two buttons are centering differently? How can I make the one on the left center properly, both left-to-right and top-to-bottom, while keeping it a proper <button>?

Thanks.

.control-panel {
  border: 1px solid #0000;
  display: flex;
  justify-content: space-between;
}

.button {
  border: 1px solid #000;
  border-radius: 5px;
  box-sizing: border-box;
  background-color: transparent;
  align-items: center;
  cursor: pointer;
}

svg {
  background-color: #0f84;
}
<div  style="width: 100px;">
  <button  style="height: 39px; width: 39px;"> <!-- BUTTON, BUT NOT CENTERED -->
                <svg style="height: 37px; width: 37px;" viewBox="-18.5 -18.5 37 37" xmlns="http://www.w3.org/2000/svg"><path d="M12,-12 L12,12 L-12,12 L-12,-12 Z" stroke="#000" fill="none" stroke-width="1.5"></path></svg>
            </button>
  <div  style="height: 39px; width: 39px;">
    <!-- DIV, BUT CENTERS CORRECTLY -->
    <svg style="height: 37px; width: 37px;" viewBox="-18.5 -18.5 37 37" xmlns="http://www.w3.org/2000/svg"><path d="M12,-12 L12,12 L-12,12 L-12,-12 Z" stroke="#000" fill="none" stroke-width="1.5"></path></svg>
  </div>
</div>

CodePudding user response:

Never mind. I was able to fix it by setting the padding to 0px. (Leaving it here in case someone else needs this.)

.control-panel {
  border: 1px solid #0000;
  display: flex;
  justify-content: space-between;
}

.button {
  padding:0;
  border: 1px solid #000;
  border-radius: 5px;
  box-sizing: border-box;
  background-color: transparent;
  align-items: center;
  cursor: pointer;
}

svg {
  background-color: #0f84;
}
<div  style="width: 100px;">
  <button  style="height: 39px; width: 39px;"> <!-- BUTTON, BUT NOT CENTERED -->
    <svg style="height: 37px; width: 37px;" viewBox="-18.5 -18.5 37 37" xmlns="http://www.w3.org/2000/svg">
      <path d="M12,-12 L12,12 L-12,12 L-12,-12 Z" stroke="#000" fill="none" stroke-width="1.5"/>
    </svg>
  </button>
</div>

  •  Tags:  
  • Related