CSS Center Image In div example with explanation
CSS 0 CommentsIn this article, we will learn how to center Image in div using CSS with examples and its detailed property-by-property explanation.
Here we will see a quick example then we will talk in detail, Add the below CSS to your image and it will make your image horizontally centered.
.centerImage { display: block; margin: 0 auto; }
One thing you need to remember that your div
width must be greater than your image width because, In fact, It’s not possible to center anything when the parent width is smaller than child :D.
There are too many ways to make things center in CSS but in this post, we are not gonna talk about all of them as this is about how to center image in div.
See the example below:
See the Pen RwwmWMK by Rajnish (@rajnish_rajput) on CodePen.
Explanations:
In the above example, I simply made a div
and put an image using img
tag inside it,
div tag
For div
CSS I gave it 100% width to make sure that div will take all the width and will be bigger than its child img
.
The second property background is because you can easily identify that the image is in the center.
img tag
For img
CSS, first of all, I gave width 200px to make sure that it will look smaller than its parent so that you can get a clear view.
I know, I know, what if there is a case that you just can’t define the width?
So, It’s totally okay if you remove the width from img
tag it will still be in the center.
Second, and the important property is display:block
. It is important because you have to make img
tag a block-level element to put it in the center with margin property because by default img
tag is an inline element.
Third, where magic happened is margin property just set right and left margin
to auto
and it will be in the center always.
That’s all. Thanks for reading and share it with love. For more about CSS or JavaScript
Leave a Reply