Top community members
All Questions Ask Question

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

CSS - div image margin auto is not working

1 answers
1 points

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 comments
read following article https://dirask.com/posts/CSS-center-element-horizontally-and-vertically-pJO6gj
Greg
Now
Add comment
1 answers
3 points

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

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more