How to center an image in HTML

Centering images in web design ensures they align perfectly with the content and layout, enhancing visual appeal and readability. This article provides step-by-step instructions on how to center images using Bootstrap and plain CSS, suitable for responsive designs and ensuring seamless integration.


Using Bootstrap

This example uses Bootstrap utility classes. mx-auto sets the horizontal margins to auto, centering the image within its container. The d-block class changes the image's display property from the default inline to block, which is necessary for mx-auto to work.

Centered Image
        
            
          <img src="path/to/your/image.jpg" class="mx-auto d-block" alt="Centered Image">
          
        
    

Using CSS Flexbox

In this example, the container div is styled to behave as a flex container .display: flex, and justify-content: center; centers the image horizontally within the container.

Centered Image
        
            
          <div style="display: flex; justify-content: center;">
            <img src="path/to/your/image.jpg" alt="Centered Image">
          </div>
          
        
    

Using CSS Grid

This approach sets the container div to a grid container. The place-items: center; is a shorthand for setting both align-items and justify-items, which centers the image both vertically and horizontally within its container.

Centered Image
        
            
          <div style="display: grid; place-items: center;">
            <img src="path/to/your/image.jpg" alt="Centered Image">
          </div>
          
        
    

Using Inline CSS

For a quick solution without any external stylesheets or frameworks, inline CSS can be used. This method involves direct inline styling. Setting the image to display: block; and margin: auto; ensures it is centered horizontally within its parent element.

Centered Image
        
            
          <img src="path/to/your/image.jpg" style="display: block; margin: auto;" alt="Centered Image">