Languages

CSS - div image margin auto is not working

1 points
Asked by:
Root-ssh
175460

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?

1 answer
3 points
Answered by:
Root-ssh
175460

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join