Center image using text-align center with CSS


The text-align center is generally used to center text of an element. However, we can also center an image using the same text-align property. First, let us see how to center align a text, then we will center an image using the text-align. Additionally, we will also align an image horizontally and vertically as well.

Center a Text Using the Text-align Property in CSS

Let us first see how to center a heading using the text-align property −

h1 {
   text-align: center;
}

Example

Let us now see the example to center a text on an HTML web page −

<!DOCTYPE html>
<html>
<head>
   <style>
      h1 {
         text-align: center;
      }
   </style>
</head>
<body>
   <h1>Demo Heading</h1>
   <p>This is demo text.</p>
</body>
</html>

Center an Image Using the Text-align Property in CSS

We will now see how to center an image using the text-align property in CSS. The center value of the text-align property is used for this −

.myimg {
   text-align: center;
}

The following image we have set under div −

<div class="myimg">
   <img src="https://www.tutorialspoint.com/jsf/images/jsf-mini-logo.jpg" />
</div>

Example

Let us now see the example to center an image on an HTML web page −

<!DOCTYPE html>
<html>
<head>
   <style>
      .myimg {
         text-align: center;
      }
   </style>
</head>
<body>
   <h1>Centering an Image</h1>
   <div class="myimg">
      <img src="https://www.tutorialspoint.com/jsf/images/jsf-mini-logo.jpg" />
   </div>
</body>
</html>

Center an Image Horizontally

To center an image using the display property in CSS and set it to flex. The horizontal position is set using the justify-content property with value center

div {
   display: flex;
   justify-content: center;
}

Example

Let us see an example −

<!DOCTYPE html>
<html>
<head>
   <style>
      div {
         display: flex;
         justify-content: center;
      }
   </style>
</head>
<body>
   <h1>Centering an Image Horizontally</h1>
   <div>
      <img src="https://www.tutorialspoint.com/jsf/images/jsf-mini-logo.jpg" />
   </div>
</body>
</html>

Center an Image Vertically

Let us now see how to center an image using the display property in CSS and set it to flex. The vertical position is set using the align-items property with value center

div {
   display: flex;
   align-items: center;
}

Example

Let us see an example −

<!DOCTYPE html>
<html>
<head>
   <style>
      div {
         display: flex;
         align-items: center;
      }
   </style>
</head>
<body>
   <h1>Centering an Image Vertically</h1>
   <div>
      <img src="https://www.tutorialspoint.com/jsf/images/jsf-mini-logo.jpg" />
   </div>
</body>
</html>

Updated on: 30-Oct-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements