html - 为什么当我使用垂直对齐时,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>
解决方案
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>
推荐阅读
- flutter - Dart:forEach 方法参数接受 void 但即使返回 int 也可以
- linkedin - Linkedin 最新更新/活动
- reactjs - How to get data from prop.location.state in react?
- c - 如何在不使用 stat() 的情况下检测到我在 C 中打开()了一个目录?
- javascript - Json Pipe - 无法将字段设置为空
- c++ - Index size of an array
- java - 为什么会这样编译?覆盖方法不是异常的子类
- appveyor - Building different Solution Configuration in Appveyor for each platform
- python - 如何为可执行的 python 脚本包含可选输入?
- cefsharp - CEFSharp 的 ECCN(出口管制分类号)