首页 > 解决方案 > 为什么当我使用垂直对齐时,img 不能垂直居中?

问题描述

当我使用垂直对齐时,img 不能垂直居中,我真的不明白为什么。

h1 {
  position: relative;
  line-height: 50px;
  background: blanchedalmond;
}

h1::before {
  content: '';
  position: absolute;
  top: 50%;
  width: 100%;
  border-top: 1px solid green;
}

img {
  width: 30px;
  height: 30px;
  vertical-align: middle;
}
<h1>
  <img src="https://img01.yzcdn.cn/vant/cat.jpeg" />
  vertical-align middle
</h1>

标签: htmlcssvertical-alignment

解决方案


First, you don't have vertical align middle applied. You have posted it as text in your HTML but as such, it also only works as text but not as a code command.

Then, vertical-align: center; only works in combination with tables or table-cells. So you would need to apply: display: table-cell;. However, the more modern solution would be flexbox. Use: h1 { display: flex; align-items: center; } and the image will be vertically centered within the <h1> tag.

Then you have 2 issues:

The critical issue: <h1><div></div></h1> is an invalid HTML markup that will neither pass the W3C nor the WHATWG markup check. A <div> cannot be a child within a header tag.

The minor issue is with the <img /> tag. Since HTML5 the image tag is an empty tag. Means it does not have a closing tag nor does it have a slash at the end. It's simply written <img>. Only a few frameworks/libraries still use the slash.

h1 {
  position: relative;
  line-height: 50px;
  background: blanchedalmond;
  display: flex;
  align-items: center;
}

.line {
  position: absolute;
  top: 50%;
  width: 100%;
  border-top: 1px solid green;
}

img {
  width: 30px;
  height: 30px;
}
<h1>
  <div class="line"></div>
  <img src="https://img01.yzcdn.cn/vant/cat.jpeg" />
  vertical-align middle
</h1>


推荐阅读