How to center an image with CSS?


To center an image on a web page, we have used the display, margin-left, and margin-right properties. Let us first see the display property.

The Display Property

To set an element as a block element, set the display property to block. In this case, our element is an image −

display: block;

The Margin-left Property

To set the left margin of an element, use the margin-left property in CSS. We have set the left margin for the image as auto that allows the web browser to calculate the left margin −

margin-left: auto;

The Margin-right Property

To set the right margin of an element, use the margin-right property in CSS. We have set the right margin for the image as auto that allows the web browser to calculate the left margin −

margin-right: auto;

Center an Image

Apply all the above properties on the image to center align an image −

img {
   display: block;
   margin-left: auto;
   margin-right: auto;
   width: 50%;
}

Example

The following is the code to center an image with CSS −

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <style>
      img {
         display: block;
         margin-left: auto;
         margin-right: auto;
         width: 50%;
      }
   </style>
</head>
<body>
   <h1 style="text-align: center;">Example of centering an image</h1>
   <img src="https://www.tutorialspoint.com/compiler_design/images/compiler-design-mini-logo.jpg">
</body>
</html>

Updated on: 16-Nov-2023

455 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements