How to Vertically Center an Image Inside a div using CSS?

There are different ways to vertically center an image inside a div element in CSS. However, the easiest and most efficient way is to use the CSS flexbox model on the div element.

In this method, you have to just make the div element a flex container by applying display: flex; on it.

When you apply display: flex; on an element, it starts behaving like a flex container, and then you can use flexbox properties like justify-content, align-items, etc. to center the flex items horizontally and vertically.

Let’s say we have a div element that contains an image inside of it. Our task is to vertically center the image inside the div element:

<div class="parent">
    <img src='images/cat.jpg' width=200 height=200>
</div>

Now, to center this image vertically inside the div, we will set the align-items property to center and to center it horizontally, we will have to just set the justify-content property to center. That’s it.

Example:

.parent{
    display: flex;
    align-items: center;     /* Center vertically */
    justify-content: center; /* Center horizontally */
    border: 2px solid red;
    height: 300px;
}

Method 2 – Using Position Absolute

In this approach, we set the position of the image to absolute so that it can be positioned relative to its nearest positioned element.

But, we want to position it relative to its parent div element, therefore, we will have to apply the position: relative; on the div itself.

Now, to center the image vertically inside the div, we need to set the top and bottom proeprties to 0 and then apply margin:auto; on it.

If you also want to center the image horizontally, you have to set the left and right properties to 0.

See the below working example:

Example:

.parent{
    position: relative;
    border: 2px solid red;
    height: 300px;
}
.parent img{
    position: absolute;
    top: 0;       
    bottom: 0;    
    left: 0;
    right: 0;
    margin:auto;
}

Method 3 – Using transform Property

This method is almost similar to the previous method we discussed.

In this approach, we first shift the image by 50% both horizontally as well as vertically. But doing so, only centers the top-left corner of the image, not the whole image.

Therefore, we have to translate it back by -50% using the transform property:

Example:

.parent{
    position: relative;
    border: 2px solid red;
    height: 300px;
}
.parent img{
    position: absolute;
    top: 50%;    /* Shift vertically */
    left: 50%;   /* Shift horizontally */
    transform: translate(-50%, -50%);
}

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.