Languages

CSS - div image margin auto is not working

1 points
Asked by:
Root-ssh
66625

How do I center image inside div? I tried with CSS - margin: auto, but it doesn't work.

Below code:

// ONLINE-RUNNER:browser;

<!doctype html>
<html lang="en">
<body>

  <div style="margin: auto;">
    <img src="https://dirask.com/static/bucket/1595077895979-mJdQ42oD24--image.png" 
         width="200px">
  </div>

</body>
</html>

Output:

I expect this picture to be centered with margin: auto, but it is not. How do I fix this?

Image used in this example:

1 answer
3 points
Answered by:
Root-ssh
66625

Quick solution:

// ONLINE-RUNNER:browser;

<!doctype html>
<html lang="en">
<body>

  <div>
    <img src="https://dirask.com/static/bucket/1595077895979-mJdQ42oD24--image.png"
         width="200px" style="margin: auto; display: block;">
  </div>

</body>
</html>

Output:

The picture is centered.

The code from question is almost correct. But we need to add margin: auto to img tag instead of div tag. And additionally we need to add display: block.

Solution to this problem is to add:

<img src="photo.jpg" style="margin: auto; display: block;">

 

0 comments Add comment
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join