<svg> 作为第一个 child 的 Flexbox 元素向上 mis-aligned

Flexbox element with <svg> as first child gets mis-aligned upwards

如果一个元素有 display: inline-flex 并且包含一个 <svg> 作为第一个 child,该元素被推上去。

用例:一个按钮可以有一个 <svg> 图标作为 children。在文本之前、之后或中间。

使用 flexbox 我们可以对齐图标并在图标和文本之间添加间距,而不管它们出现的顺序如何(并且不必将文本换行在 <span> 中)。

BUG: 但是,如您所见,左侧带有图标的按钮(即第一个 <svg> child)被移动了与其他两个相比!

button {
  /* This will center align the icon (vertically)
   * and add 5px margin on each side of it */
  display: inline-flex;
  align-items: center;
  grid-gap: 5px;

  font-size: 16px;
  line-height: 20px;
}
<div>
  <button>Text</button>
  <button>
    <svg width="14" height="14" viewBox="0 0 100 100">
      <circle cx="50" cy="50" r="50" fill="hotpink" />
    </svg>
    Text
  </button>
  <button>
    Text
    <svg width="14" height="14" viewBox="0 0 100 100">
      <circle cx="50" cy="50" r="50" fill="hotpink" />
    </svg>
  </button>
</div>

没有 inline-flex 控制布局,按钮彼此对齐(但按钮内的图标未居中对齐)。

button {
  font-size: 16px;
  line-height: 20px;
}
<div>
  <button>Text</button>
  <button>
    <svg width="14" height="14" viewBox="0 0 100 100">
      <circle cx="50" cy="50" r="50" fill="hotpink" />
    </svg>
    Text
  </button>
  <button>
    Text
    <svg width="14" height="14" viewBox="0 0 100 100">
      <circle cx="50" cy="50" r="50" fill="hotpink" />
    </svg>
  </button>
</div>

如果您将 vertical-align: middle 添加到父元素,即使它有一个 <svg> 作为第一个子元素,它也不会向上移动。

button {
  /* This will center align the icon (vertically)
   * and add 5px margin on each side of it */
  display: inline-flex;
  align-items: center;
  grid-gap: 5px;

  /* Align correctly even if the first child is an svg */
  vertical-align: middle;

  font-size: 16px;
  line-height: 20px;
}
<div>
  <button>Text</button>
  <button>
    <svg width="14" height="14" viewBox="0 0 100 100">
      <circle cx="50" cy="50" r="50" fill="hotpink" />
    </svg>
    Text
  </button>
  <button>
    Text
    <svg width="14" height="14" viewBox="0 0 100 100">
      <circle cx="50" cy="50" r="50" fill="hotpink" />
    </svg>
  </button>
  <button>
    Text
    <svg width="14" height="14" viewBox="0 0 100 100">
      <circle cx="50" cy="50" r="50" fill="hotpink" />
    </svg>
    text
  </button>
  <button>
    <svg width="14" height="14" viewBox="0 0 100 100">
      <circle cx="50" cy="50" r="50" fill="hotpink" />
    </svg>
    Text
    <svg width="14" height="14" viewBox="0 0 100 100">
      <circle cx="50" cy="50" r="50" fill="hotpink" />
    </svg>
  </button>
</div>