0

Why is the image not centered here?

#image {
  margin: 0 auto;
}
<div id="image">
  <img src="https://placekitten.com/200/300">
</div>

But it works perfect with a <center> tag.

My fiddle

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
KC Here
  • 33
  • 3
  • Possible duplicate of [Center image in div horizontally](http://stackoverflow.com/questions/9980531/center-image-in-div-horizontally) – Peter VARGA Aug 03 '16 at 14:37
  • 1
    Possible duplicate of [How to make an image center (vertically & horizontally) inside a bigger div](http://stackoverflow.com/questions/388180/how-to-make-an-image-center-vertically-horizontally-inside-a-bigger-div) and a multitude of similar answers found by searching SO. – Rob Aug 03 '16 at 14:37

4 Answers4

4

JSFiddle here. Your <div> needs to be 100% in width, and the image has to be a block element; try this CSS:

#image {
    width: 100%;
}
#image img {
    margin: 0 auto;
    display: block;
}

Alternatively:

#image {
    width: 100%;
    text-align: center;
}

This will center <img> tags, as they have display: inline-block; by default. Only display: block elements can be centered using margin: 0 auto;.

Quick summary:

  • Horizontally center block displayed elements using margin: 0 auto; on the element, to center relative to the parent element's width;
  • Horizontally center inline-block displayed elements using text-align: center; on the parent element, to center relative to the parent element's width.
Nick Bull
  • 9,518
  • 6
  • 36
  • 58
0

Since an image is not a block element, it's enough just to add text-align: center; to its parent.

#image{
  text-align: center;
}
Mila
  • 598
  • 4
  • 9
0

You can use text-align:center;

#image{
    margin-left: auto;
    margin-right: auto;
    text-align: center;
  
     }
<div id="image">
     <img src="https://scontent-kul.xx.fbcdn.net/v/t1.0-0/s526x395/13934860_132991530474366_7559506120027031422_n.jpg?oh=54eb36c2f2b2383712a6dcf1da2cd638&oe=58212A26">
     </div>
Md. Nasir Uddin Bhuiyan
  • 1,598
  • 1
  • 14
  • 24
0

Or you could just use flexbox

#image {
  height: 90vh;
  width: 90vw;
  display: flex;
  justify-content: center;
  align-items: center;
}

You don't need the 90vh or 90vw but you do need to give the height and width some value. Whether it's in px or % is up to you.

tcasey
  • 399
  • 2
  • 7