Open In App

How to Center an Image using text-align Property in CSS ?

Last Updated : 09 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Aligning an image horizontally within a container can be difficult, in this article we will explore how to center an image by using the text-align property in CSS.

The text-align property in CSS is used to specify the horizontal alignment of text in an element ie., it is used to set the alignment of the content horizontally, inside a block element or table-cell box.

To center an image horizontally using the CSS text-align property, apply it to the parent element. Set text-align: center; to align the image at the center. This works because the text-align property also affects inline-block and inline elements, including images.

We have 2 approaches to center an image with the help of the text-align property.

Center an Image using text-align: center Property

To center an image using the text-align: center property, we must place our image inside a block-level element such as Div and P tag.

Syntax:

.container {
    text-align: center;
}

Example: Here we are using a block-level element as a parent element of our image.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        .container {
            text-align: center;
            border: 1px dashed;
            width: 400px;
            height: 600px;
        }
    </style>
</head>
  
<body>
    <h2 style="color:green;">
        GeeksforGeeks
    </h2>
    <div class="container">
        
        <!-- Block parent element -->
        <img src=
             alt="placeholder image">
    </div>
</body>
  
</html>


Output:

 

Center an Image using display: block along with text-align Property

In the second approach, if our parent element is not a block-level element we use the display: block property along with the text-align property.

Syntax:

.container {
    text-align: center;
    display: block;
}

Example: Here our parent element is not a block element, so we use the display: block property along with the text-align property.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        .container {
            text-align: center;
            display: block;
            border: 1px dashed;
            width: 400px;
            height: 600px;
        }
    </style>
</head>
  
<body>
    <h2 style="color:green;">
        GeeksforGeeks
    </h2>
    <span class="container">
        
        <!-- Inline parent element -->
        <img src=
             alt="placeholder image">
    </span>
</body>
  
</html>


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads