Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I vertically center an image with flex when the parent container has align items of baseline?

What I have is the following:

enter image description here

I have an icon on the left that represents a product. Then in H1, I have a product category, and with an h2, I have a product name.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The icon, h1, and h2 are in a parent div with flex and align-items value of baseline. So the text is baseline aligned.

Due to the dynamic nature of how the page title here is retrieved, the icon has to be in this parent div that is baseline aligned.

How can I vertically center the icon within this parent div with flexbox? I know how to accomplish this with vertical alignment and setting line height, but I’d prefer a flexbox approach.

Parent:

.parent {
  display: flex;
  align-items: baseline;
}

HTML skeleton:

<div class="parent">
  <div>Icon</div>
  <div>Product Category</div>
  <div>Product Name</div>
</div>

>Solution :

You can set align-self:center on the icon if you cannot change the parent div’s align-items value to center. Find below an example:

.parent {
  display: flex;
  align-items: baseline;
  gap:1rem; /* added just for readability, you can remove it */
}


.parent div:first-child{
  align-self:center;
}
<div class="parent">
  <div>Icon</div>
  <h1>Product Category</h1>
  <h2>Product Name</h2>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading