0

I'm hoping there's just something major I'm missing here with inline-flex.

I'm using display: inline-flex and the order of the 2 items inside of the element change how the element aligns with its siblings.

In this scenario I have 3 anchor tags each with some text and an "icon" element. On the 2nd anchor tag I've put the "icon" element as the first child which causes the element to not align with its sibling anchor tags.

.item {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 4px 8px;
}

.icon {
  display: inline-block;
  width: 20px;
  height: 20px;
  background: red;
}
<a href="#" class="item">
  item
  <span class="icon"></span>
</a>
<a href="#" class="item">
  <span class="icon"></span>
  item
</a>
<a href="#" class="item">
  item
  <span class="icon"></span>
</a>

Here's a CodePen that shows the issue: https://codepen.io/Fernker/pen/BaVjvXB

TylerH
  • 20,799
  • 66
  • 75
  • 101
Fernker
  • 2,238
  • 20
  • 31

2 Answers2

3

Here are two options:

  1. Set vertical-align on the .item {} selector; you can use the value bottom, middle, or top... whichever one fits your needs.

  2. Transpose the position of the "item" text and the <span> in your second/middle <a> link.

TylerH
  • 20,799
  • 66
  • 75
  • 101
1

I would wrap them in a div and use align-items:center in this div. Im not a big fan of vertical-align. There can be some unwanted issues / side effects. Of course it depends where and how you use it, but some issues are described here: https://christopheraue.net/design/why-vertical-align-is-not-working

.container {
  display:flex;
  align-items:center;
  gap:16px;
}

.item {
  display: inline-flex;
  gap: 5px;
}

.icon {
  display:inline-block;
  width: 20px;
  height: 20px;
  background: red;
}
<div class="container">
  <a href="#" class="item">
    item
    <span class="icon"></span>
  </a>
  <a href="#" class="item">
    <span class="icon"></span>
    item
  </a>
  <a href="#" class="item">
    item
    <span class="icon"></span>
  </a>
</div>
  • This is a valid solution for sure, although if your answer is essentially "don't use `vertical-align` because it doesn't always work", it would be better to mention why/where it doesn't work _in the answer_ rather than just linking to a 3rd party site. Especially given there's already an answer showing it _does_ work for the code OP provided. – TylerH Nov 02 '22 at 13:11
  • I didn't advice to not use vertical-align. Just mentioned that there can be issues using it and I've provided a source where its explained why. And since the question already uses flex box this is the best answer in my opinion. – Chris Schober Nov 07 '22 at 15:55