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?
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>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;
    }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With