2

this may be a simple question but I can't figure out why this image (id=daftfont) wont center? Currently I am just trying to center these two images on the page. Margin:auto; worked for the second image just fine, however the first image wont center. I am a beginner so I'm having trouble figuring out why. I appreciate any insight.

    <style>

    body{
     background-color: black;
     }

    #daftfont{
     margin:auto;
     width:170px;
     }

    #daft{
     margin:auto;
     width:200px;
     height:200px;
     border-style:solid;
     border-color:white;
    }

    </style>


     <img id="daftfont" src="https://i.ibb.co/nbFjzX6/daft-punk-transparent.png">
  
     <div id="daft">
      <img src="https://i.ibb.co/4pFZZc4/Daft-Punk-200x200.jpg">
     </div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Bamblagram
  • 41
  • 6

2 Answers2

2

To center an html element with margin: auto, this need to have display: block. In the second case the div is block:

Add this rule to your image to center it:

#daftfont{
 display: block; /* add this */
 margin:auto;
 width:170px;
}

body{
 background-color: black;
 }

#daftfont{
 display: block;
 margin:auto;
 width:170px;
 }

#daft{
 margin:auto;
 width:200px;
 height:200px;
 border-style:solid;
 border-color:white;
}
<img id="daftfont" src="https://i.ibb.co/nbFjzX6/daft-punk-transparent.png">

<div id="daft">
  <img src="https://i.ibb.co/4pFZZc4/Daft-Punk-200x200.jpg">
</div>
Hans Felix Ramos
  • 4,264
  • 3
  • 16
  • 40
2

Use display:block on img#daftfont to make margin active.

Explanation: img by default have display as inline, however margin takes effect for elements with display block, so you need to change display property on img#daftfont. In second case margin is applied on a div element which by default has display block, so no problem happens. Another solution is to wrap the img#daftfont inside a div element and set margin:auto to that, like you do in second case.

  <style>

    body{
     background-color: black;
     }

    #daftfont{
     margin:auto;
     width:170px;
     display:block;
     }

    #daft{
     margin:auto;
     width:200px;
     height:200px;
     border-style:solid;
     border-color:white;
    }

    </style>


     <img id="daftfont" src="https://i.ibb.co/nbFjzX6/daft-punk-transparent.png">
  
     <div id="daft">
      <img src="https://i.ibb.co/4pFZZc4/Daft-Punk-200x200.jpg">
     </div>
Nikos M.
  • 8,033
  • 4
  • 36
  • 43