What is the principle of vertical alignment of this kind of picture?


< html >
< head >

<title></title>

< / head >
< body >
< div style= "text-align: center; width: 500px10 height Heights 200px; line-height:200px; border: green solid 1px;" >
https://www.baidu.com/img/bai.; style= "display: inline-block; vertical-align: middle;" / >
< / div >
< / body >
< / html >

1. Set the row height on the parent element. (generally speaking, shouldn"t you set the line height of the child element to be equal to the height of the parent element? the picture may not be as high as the row height, so it is invalid? )
2. Set the Vertical br in img! In the description of W3C, please see the following figure

it says to align vertically according to the baseline of the line in which the element is located, and the following says to place the secondary element in the middle of the parent element! (writing vertical-align on img alone cannot be centered vertically)

I"m lost! So how on earth do you use this line-height and vertical-align?

Don"t talk to me about

ps, other display:table; and absolute positioning. I know! I just want to know how the above code explains ~

Mar.30,2021

this vertical-align requires multiple elements to achieve a centered effect. A single element does not work, and it is inline-block

.

for example:

<style>
    .box i{ display:inline-block; width:10px; height:100px; background:red; vertical-align:middle; }
    .box img{ vertical-align:middle; }
</style>
<div class="box">
    <i></i>
    <img>
</div>

in this case, the picture and the I tag are vertically centered

.

using this principle, we can simplify and use pseudo elements to center vertically

.
<style>
    .mfix:before{content:'';display:inline-block; width:0; height:100%; vertical-align:middle;}
    .mfix>*{display:inline-block;vertical-align:middle;}
</style>
<div class="box mfix">
    <img>
</div>

add a mfix class name to the parent to achieve vertical centering of child elements

complete demo code

https://codepen.io/xboxyan/pe.


take a look at the article by Zhang Xinxu: pictures of variable size, Multiline text is centered horizontally and vertically
css line height line-height Some in-depth understanding and application

Menu