-2

Why the image does not go to the center in HTML? I have entered margin to auto.

<div style="margin: 20px auto" class="elem">
  <img 
     src="https://image.freepik.com/free-vector/online-test-concept-illustration_114360-5486.jpg"
     alt="" />
</div>
t.niese
  • 39,256
  • 9
  • 74
  • 101

5 Answers5

5

You can either...

Add text-align:center; to your div

OR

Add display:block; margin: auto; to your image

Duenna
  • 2,186
  • 2
  • 14
  • 17
1

.elem{
    border: 1px solid;
}
.elem img{
    margin: auto;
    display: block;
    height: 100px;
    width: 100px;
}
<div class="elem">
  <img 
     src="https://image.freepik.com/free-vector/online-test-concept-illustration_114360-5486.jpg"
     alt="" />
</div>
Selaminko Elam
  • 173
  • 1
  • 14
0

you should use style "text-align: center" then it will go to center

<div style="margin: 20px auto; text-align: center;" class="elem" >
    <img
      src="https://image.freepik.com/free-vector/online-test-concept-illustration_114360-5486.jpg"
      alt=""
    />
   </div>
0

Here is a solution:

   <div style="margin: 20px auto" class="elem">
     <img
     style="display: block; margin: auto;"
     src="https://image.freepik.com/free-vector/online-test-concept- 
     illustration_114360-5486.jpg"
     alt=""
     />
   </div>
0

At first you have to check the display property of your element. And margin auto works only with those elements which has display property as "block". So if you still want to use margin:auto, you have to use with Display block. Otherwise you can use text-align:center