How to align center image in a div? Horizontal/Vertical/Both
38704 Feb 2022
How an image can be centered either vertically or horizontally or horizontally and vertically at same time.
Any easily understandable method will be appreciated.
Thanks for the answer in advance.
0 likes
raman gulati answered this.
04 Feb 2022
Aligning images on different axis is a difficult job to do. When you try to align it using CSS, either it has no effect or doesn"t give the desirable results. But using the method depicted below, you can align center all images either vertically or horizontally or on the both the axis.

For this tutorial we will use the following markup:-
<div>
<img src="something.jpg" />
</div>
In the above code, there will be an image placed at the left top corner inside the div.
To change it"s alignment on different axis we will divide all the process in 3 part/cases.
Case no I :- Align the image horizontally.
To align images horizontally, we will use these lines of CSS:
div{
display: flex;
justify-content: center;
}
In the above code we have not applied any css on img element. Applying display flex property on the container div, we have changed the display property from block to flex, so we are now able to use some another properties like justify-content on the div. Once we apply justify-content: center;, everything inside the div get centered Horizontally.
Case no II :- Align the image vertically.
Such kinds of cases comes in scenario when there is a container div with a fixed height. Assume we have a div with the height of 1000 px containing an image with the height of 600px. Here pushing the image to the center from top seems difficult, but can be done using following 2 lines of extra CSS:
div{
height: 1000px; //fixed height
display: flex;
align-items: center;
}
Case no III :- Align the image horizontally and vertically.
It"s very easy to align any images in center horizontally and vertically. You just need following 3 lines of CSS:
div{
display: flex;
align-items: center;
justify-content: center;
}
After using above code, your image will be centered horizontally and vertically.
Keep one thing in mind that you must have only one image in the div. Otherwise you will have some problem while aligning the image.
Since CSS flex is an advanced version of CSS, multiple images can also be centered but you will need to learn more about CSS flexbox.
Thanks!!!
1 likes
Top related questions
CSS not working in HTML - कौन कौन से कारण हो सकते हैं?
12 Feb 2022 368
What is Html attributes?In English.
28 Jul 2022 204
HTML में background color कैसे सेट करें?
11 Feb 2022 355
Related queries
Latest questions
Income issues
15 Apr 2025 1
चीन अमेरिकी वस्तुओं पर टैरिफ बढ़ाकर 125% करेगा।
11 Apr 2025 2
सुप्रीम कोर्ट वक्फ संशोधन पर सुनवाई करेगा।
10 Apr 2025 5
Payment
07 Apr 2025 2