Home > Enterprise >  How to align Center to Svg icon
How to align Center to Svg icon

Time:04-17

I have a svg icon ,this align is left ,i want to fix align center , i use this code but its not working.

.parent{
display: flex;
align-items: center;
font-size: 13px;
}
span{
margin-right:10px
}

here is the result

look at svg icon and it's not in center

by the way i use flex:

svg{ 
display: flex;
align-items: center;
justify-content:center;
}

I use text-align:center too but it's not working

CodePudding user response:

If you mean vertically align center, you can use vertical-align: middle style property. That will align the svg vertically.

CodePudding user response:

First, you should rename your css classes I don't see the .parent class on your inspected element

And I think the best way to handle this is to add a parent to your svg and let the parent handle the positioning

For example :
CSS

.parent-svg {
 display:flex;
 justify-content:center;
 align-items:center;
}

HTML

<div >
<span>Text</span>
<div >
 <svg />
</div>

CodePudding user response:

align-items: center will align all children vertically centered.

justify-content:center aligns all children horizontally centered.

body {
  font-size: 5em;
  font-family: 'Segoe UI', sans-serif;
}

svg {
  height: 1em;
  /* optional: additional vertical offset */
  transform: translateY(1%);
}

.parent {
  display: flex;
  align-items: center;
  justify-content: center;
}

span {
  margin-right: 10px
}
<div >
  <span>
    Example text
  </span>
  <svg  id="icon-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"></path>
  </svg>
</div>

If your icon is not aligned as desired you could add some vertical offset via transform: translateY(X%). The visual alignment also depends on your svg viewBox.

You don't need any flex properties for your icon – doesn't have any effect on svg child elements regarding layout.

Further reading: css-tricks: A Complete Guide to Flexbox

  • Related