Search code examples
htmlcssalignment

How can I center this picture vertically and horizontally?


I have a box that is a variable width and height. In my example I want to center the picture halfway down the box. What is the best way to approach this with just CSS? I'd rather not use any JavaScript if I dont have to.

Example at: http://codepen.io/wesbos/pen/Ehour

my HTML:

<div class="box">
  <img src="http://placekitten.com/200/200">
</div>

My CSS:

.box {
  width:400px;
  height:400px;
  border:1px solid red;
  text-align:center;
}

Solution

  • You could make the DIV a table-cell and then use vertical-align property:

    .box {
      width:400px;
      height:400px;
      border:1px solid red;
      text-align:center;
      vertical-align:middle;    
      display: table-cell;
    }
    
    img{
      display: inline-block;
    }