Three ways to center CSS images horizontally and vertically

Three ways to center CSS images horizontally and vertically

set line height

We know that the img element is an inline fast element, so first set the text in the parent element of the image element to be horizontally centered, and the line height is consistent with the overall height.
The second most important thing is to set the vertical-align attribute of the image element to middle, which defines the vertical alignment of the baseline of the inline element relative to the baseline of the row where the element is located.
Code example:

<style>
	div {
    
    
		height: 300px;
		text-align: center;
		line-height: 300px;
	}
	img {
    
    
		vertical-align: middle;
	}
<style>

<div>
	<img src="./pic.png">
</div>

Using positioning and translate

The specific method is to first use positioning to offset the picture to the right and down by 50% of the parent element, and then offset it to the left and up by 50% relative to itself, so that the picture is horizontally and vertically centered in the parent element.
Code example:

<style>
	div {
    
    
		height: 300px;
		position: relative;
	}
	img {
    
    
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
	}
<style>

<div>
	<img src="./pic.png">
</div>

Use flexbox

Sets the parent box of the image element to flexbox, so that the items are centered on both the main axis and the cross axis.

<style>
	div {
    
    
		height: 300px;
		display: flex;
		justify-content: center;
		align-items: center;
	}
<style>

<div>
	<img src="./pic.png">
</div>

Guess you like

Origin blog.csdn.net/weixin_44287328/article/details/126854191