CSS Center an Images

Please Share On:

Definition:

Today, you will learn how to center an image using CSS code. To center an image you need to set left and right margin to auto and make an element a block.

See an image which is centered in a container.

Syntax:

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

Source Code:

<!DOCTYPE html>
<html>
  <head>
    <style>
      body {
        margin:20px;
      }

      .container {
        width: 100%;
        background-color: lavender;
        box-shadow: 0 8px 8px 2px rgba(0, 0, 0, 0.6);
        margin-bottom: 15px;
      }
      
      img { 
        margin-left: auto;
        margin-right: auto;
        display: block;
        width: 50%
      }

      .title, h2 { 
        text-align: center;
        padding: 10px 20px;;
      }
    </style>
  </head>
  <body>

    <h2>Center an Images</h2>

    <div class="container">
      <img src="https://www.elsebazaar.com/blog/wp-content/uploads/2020/11/Sydney-Harbour-Bridge-View.jpg" alt="Sydney Harbour Bridge" > 
      <div class="title">
        <p>Sydney Harbour Bridge</p>
      </div>
    </div>

  </body>
</html>							
					

Output

Click “TRY IT YOURSELF” to see the results.


Donate to support writers.


You may be interested in the following topics:

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright @2023. All Right Reserved.


Social media & sharing icons powered by UltimatelySocial