Place img and span tags in Div tags to achieve vertical and horizontal centering

Normal default layout

Code:

<div style="width: 400px; height:400px; background-color:blueviolet">
        <img style="width: 80px; height: 80px;" src="./picture.png">
        <span style="color:white;">我是span标签</span>
</div>

The renderings are as follows: 

We first implement the text of the span tag to be vertically centered next to the image. There are two methods to achieve this.

Method 1: Recommended when only considering span text to be vertically centered next to the image

Add vertical-align: middle to the css styles of both img and span tags

Code:

<div style="width: 400px; height: 400px; background-color: blueviolet">
      <img
        style="width: 80px; height: 80px; vertical-align: middle"
        src="./picture.png"
      />
      <span style="color: white; vertical-align: middle">我是span标签</span>
</div>

The renderings are as follows:

 

Method 2: Use flex layout (recommended when considering both the whole and horizontal and vertical centering in the div)

1. First enable flexible layout for div settings. display:flex;

2. Then set the line height of the span tag to the same height as the image img. For example, my image height: 80px; set the line height for span: line-height: 80px;

Code:

<div style="display: flex; width: 400px; height:400px; background-color:blueviolet">
        <img style="width: 80px; height: 80px;" src="./picture.png">
        <span style="line-height: 80px; color:white;">我是span标签</span>
</div>

The renderings are as follows:

Furthermore, if you want to realize that the img and span are centered vertically and horizontally in the div, it is better to use flex layout.

1. Turn on the flexible box for the div (the second method used above ignores this step): add display:flex to the div style;

2. To achieve overall horizontal centering: add justify-content: center; to the div style.

3. To achieve overall vertical centering: add align-items: center; to the div style;

Code: 

<div style="display: flex;justify-content: center;align-items: center; width: 400px; height:400px; background-color:blueviolet">
        <img style="width: 80px; height: 80px;" src="./picture.png">
        <span style="line-height: 80px; color:white;">我是span标签</span>
</div>

 The renderings are as follows:

 That's it! ! !

Guess you like

Origin blog.csdn.net/m0_53703061/article/details/126307220