How to center an image in CSS?

One of the most common problems that developers generally face while working with images is their alignment and positioning in the layout.

In this tutorial, we will discuss some of the easy methods that can be very helpful to center an image both horizontally as well as vertically. So let’s get started:


Center an image using text-align property

This is the easiest method to center an image. All you need to do is put the <img> tag inside a <div> element and apply text-align: center; property on the parent <div> element. It will automatically center the image.

Here is a working example:

Example:

div{
   text-align: center;
}

Center an image using margin: auto

We can also center an image horizontally using margin: auto;. However, if you directly apply margin: auto; on the <img> element, it won’t work. This is because <img> is an inline-level element and applying maring: auto; on such elements have no effect.

Therefore, we have to apply display: block; property as well while applying margin: auto; on the <img> element. This will automatically center it horizontally.

Here is a working example:

Example:

img{
   display: block;
   margin: auto;
}

Note: It is necessary to set a fixed width of the element if you want to center align it using margin: auto;, otherwise margin: auto; have no effect on the element.


Center an image using CSS flexbox

CSS flexbox can also help us to center an image both horizontally as well as vertically.

To horizontally center an image with flexbox, first put the <img> element inside a div element and then apply display: flex; property on this div element. This will make the div element a flex container.

Once it’s done set justify-content: center; property on the div element. This will center the image inside the div element horizontally.

Here is a working example:

Example:

div{
   display: flex;
   justify-content: center;
   border: 2px solid red;
   padding: 10px;
}

Center an image horizontally and vertically using CSS flexbox

In the previous example, we saw how to center an image horizontally.

If you want to center it vertically as well, use align-items: center; on the same parent div element.

Here is an example:

Example:

div{
   display: flex;
   justify-content: center;
   align-items: center;
   height: 350px;
   border: 2px solid red;
   padding: 10px;
}

Related Properties

You can read more about all the properties used in this article here:

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts