Centering an Element in HTML and CSS

I’m currently working on a web development project and facing a challenge in centering an HTML element or an image within a container using CSS. Despite trying several methods, I can’t seem to achieve the desired alignment.

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
  <div class="container">
    <img src="example.jpg" alt="Center Me">
  </div>
</body>
</html>

i tried to put to html element text-align:center;
I’ve experimented with techniques like using text-align: center, margin: auto, flexbox, and grid, but none of them have worked as expected. The element remains off-center, and I’m struggling to figure out what’s going wrong.
I’ve created a minimal example to illustrate the issue, but I’m not sure what I’m missing in my CSS code. I’d appreciate any guidance or alternative approaches to centering an element or image within a container using CSS.

>Solution :

To center an image on a web page, you can use CSS to style the image and its container. Here’s how you can modify your HTML and CSS to center the image:

body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh; /* This ensures the content takes up the full viewport height */
            margin: 0; /* Remove default margin to prevent unwanted space */
        }

        img {
            max-width: 100%; /* Make sure the image doesn't exceed its container width */
        }

Leave a Reply