Solve the problem that the height of the div element is not equal to the height of the content

  • 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.

Insert image description here
Insert image description here

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.

Insert image description here
If set to display: flex
Insert image description here

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.
Insert image description here

You can use this picture to understand:
Insert image description here
Let’s look at the problems I encountered:

  1. The height of the outer container element
    Insert image description here

  2. The actual height of the inner child element only
    Insert image description here

  3. 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.

Insert image description here
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;
If it is useful, please give it a thumbs up~~~

Guess you like

Origin blog.csdn.net/m0_55315930/article/details/131980996