- Let me make a conclusion first, hahahahaha. The following is a detailed introduction to the causes of the problem.
Solution
# 第一种办法,取消元素的行内元素特性,使其不存在垂直对齐特性
display:flex;
# 第二种办法
display: inline-flex;
vertical-align:top;
// vertical-align: bottom;
Ask a question
<div class="red">
<div class="box">
<img src="../assets/logo.png" alt="" />
<span>文字文字蚊子</span>
</div>
</div>
<style>
.red {
background-color: red;
}
.box {
display: inline-flex;
}
img {
width: 30px;
height: 30px;
line-height: 30px;
}
span {
font-size: 24px;
line-height: 30px;
}
</style>
The height of the normal red box should be 30px when the content is stretched. It's actually 34px.
Benefits of using display:inline-flex instead of display:flex
When there are two divs, they can be arranged horizontally and will not occupy one row.
If set to display: flex
Cause of the problem
inline-flex will change the vertical alignment of child elements
Because in an inline flexbox, the default vertical alignment of child elements is baseline alignment.
Baseline alignment means aligning an element's baseline with the baseline of adjacent elements rather than with the actual height of the content. The baseline is usually the bottom alignment line for letters in text.
It should be that the picture causes unnecessary height compensation after the left and right elements are aligned.
You can use this picture to understand:
Let’s look at the problems I encountered:
-
The height of the outer container element
-
The actual height of the inner child element only
-
Our internal child elements are set to display: inline-flex, which has the characteristics of inline elements.
Have a question? Isn't this just one element? Why does it also have an impact?
This is because the browser assumes that each line-box starts with a zero-width character (the CSS documentation calls this a strut), and includes this in the calculation of the line-box's height.Invisible characters, visible effects.
After looking at this picture, you should know why the outer element has an extra 3px impact. There is a whitespace character that interacts with our element and affects the height.
Solution
# 第一种办法,取消元素的行内元素特性,使其不存在垂直对齐特性
display:flex;
# 第二种办法,给元素设置对齐方式,不按照baseline去对齐
display: inline-flex;
vertical-align:top;
// vertical-align: bottom;