Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG inside flex misaligned when wrapped in div

I want an SVG icon of unknown size center aligned to the left of some text. I preferably want to use flex.

This is the CSS for the SVG and text container:

.container {
    background-color: pink;
    display: flex;
    align-items: center;
    margin: 10px;
    width: 200px;
}

This works fine:

<div class="container">
  <svg style="width:24px;height:24px" viewBox="0 0 24 24">
    <rect width="24" height="24"/>
  </svg>
  <div>ALIGNED ICON</div>
</div>

However, when I wrap the SVG in another div, the height of that div becomes unnecessarily big, resulting in a misalignment of the SVG and text:

<div class="container">
    <div>
        <svg style="width:24px;height:24px" viewBox="0 0 24 24">
            <rect width="24" height="24"/>
        </svg>
    </div>
    <div>MISALIGNED ICON</div>
</div>

Here is a link to CodePen


In reality, this is a React project and I use external SVG components that I don't have control over or know the size of. I can therefore not apply any styles directly to the SVG element, neither set the wrapper div height to match that of the SVG.

How do I align the SVG and text when wrapping the SVG in another div?

like image 260
darksmurf Avatar asked Sep 11 '25 06:09

darksmurf


2 Answers

The inner div must be displayed as flex as well

.container {
  background-color: pink;
  display: flex;
  align-items: center;
  margin: 10px;
  width: 200px; 
}
<div class="container">
  <svg style="width:24px;height:24px" viewBox="0 0 24 24">
    <rect width="24" height="24"/>
  </svg>
  <div>ALIGNED SVG</div>
</div>
<div class="container">
  <div style="display: flex;">
    <svg style="width:24px;height:24px" viewBox="0 0 24 24">
      <rect width="24" height="24"/>
    </svg>
  </div>
  <div>MISALIGNED SVG</div>
</div>
like image 101
Amine KOUIS Avatar answered Sep 13 '25 21:09

Amine KOUIS


Just add flex and align to that div class.

https://codepen.io/anon/pen/zeeegz

html

<div class="container">
  <svg style="width:24px;height:24px" viewBox="0 0 24 24">
    <rect width="24" height="24"/>
  </svg>
  <div>ALIGNED SVG</div>
</div>
<div class="container">
  <div class="item">
    <svg style="width:24px;height:24px" viewBox="0 0 24 24">
      <rect width="24" height="24"/>
    </svg>
  </div>
  <div>MISALIGNED SVG</div>
</div>

css

 .container {
      background-color: pink;
      display: flex;
      align-items: center;
      margin: 10px;
      width: 200px;
    }
    .item{
      display: flex;

    }
like image 40
Raahul Avatar answered Sep 13 '25 21:09

Raahul