How to center an image horizontally and vertically with CSS
By CSS, you can easily align an image to left (by default), right, top or bottom. For this, you have to use different CSS tricks. There is no single property like text-align
, that we use to align text, to align an image.
However we’re going to demonstrate the method especially to center an image. Here we’re using the most dependable method in combination with display
and margin
property.
So, no ado! Let’s enter the field-
Center an image horizontally
To center an image horizontally, you need to
- set
margin
property to auto. You can also setmargin-left: auto
andmargin-right:auto
. - set Display to
display:block;
.
For this example purpose, we’ve coded our CSS and HTML as the following-
CSS
img {
display:block;
margin-left:auto;
margin-right:auto;
width:40%;
height: 40%;
border-radius:20px;
}
HTML
<img src="https://www.netplanter.com/wp-content/uploads/2020/01/NARGIS-NARCISSUS-1.jpg"
alt="Nargis Flower">
Result

Center an image vertically
When anybody talk plainly about ‘Align an image’, he/she simply tells about horizontal alignment of that image. However, you can align an image, like other HTML elements, vertically also. In this step, you’ll capture the process of centering an image only vertically. In the next step, we’ll represent both horizontal and vertical centering of image. For this purpose, you can simply usepadding
property, though there are other possibilities.
Just do the followings-
- Use a div as a wrapper of the image.
- For the
div
setpadding
top-bottom a specific value and left-right 0. - Style the image as you wish.
We’ve just arranged the following CSS and HTML for this tiny project-
CSS
.wrapper {
border: 5px groove black;
width:100%;
padding: 100px 0;
}
img {
width:40%;
height: 40%;
border-radius: 20px;
}
HTML
<div class="wrapper">
<img src="https://www.netplanter.com/wp-content/uploads/2020/01/NARGIS-NARCISSUS-1.jpg"
alt="Nargis Flower">
</div>
Result

Center an image both horizontally and vertically
Probably, all is clear. If we combine the above-stated horizontal and vertical centering tricks, we can easily center-align an image both horizontally and vertically.Now let’s merge the codes-
CSS
.wrapper {
border: 5px groove black;
width:100%;
padding: 100px 0;
}
img {
display:block;
margin-left:auto;
margin-right:auto;
width:40%;
height: 40%;
border-radius: 20px;
}
HTML
<div class="wrapper">
<img src="https://www.netplanter.com/wp-content/uploads/2020/01/NARGIS-NARCISSUS-1.jpg"
alt="Nargis Flower">
</div>
Result

FANTASTIC! NO?