[Solved] Centering image on full page with CSS [closed]


Or, you avoid so many ‘bad’ css styling conventions and go for something like below, as stated in the thousands of other SO questions on this matter.


option 1

html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    display: table;
}
.container {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.content {
    display: inline-block;
    text-align: left;
    
}
<div class="container">
    <div class="content">
      <img src="http://placekitten.com/g/200/300" alt="" />
    </div>
</div>

option 2

.parent {
    display: table;
    height: 300px;
    background: yellow; 
    width:300px;
}
.child {
    
    display: table-cell;
    vertical-align: middle;
    text-align:center;

}
<div class="parent">
    <div class="child">
      	<div class="content">XXX</div>
    </div>
</div>

option 3

#outer {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      text-align:center;
    }
    #inner {
      width: 50%;
      height: 50%;
      top: 25%;
      margin: 0 auto;
      position: relative;
      background: orange;
    }
<div id=outer>
    <img id=inner src="http://placekitten.com/g/200/300" alt=""/>
  </div>

option 4

If you know the size of the image (and div), you could apply margins like:

.container {
  height: 300px;
  width: 300px;
  background: #eee;
  position: absolute;
   
  margin: -150px 0 0 -150px;
  left: 50%;
  top: 50%;
}
 
.box {
  height: 100px;
  width: 100px;
  background: #222;
  position: absolute;
   
  /*Centering Method 2*/
  margin: -50px 0 0 -50px;
  left: 50%;
  top: 50%;
}
<div class="container">
   <div class="box"></div>
</div>

option 5

centering text is also a doddle in css

.container {
  height: 200px; /*Set line-height to this value*/
  width: 400px;
  background: #eee;
  margin: 150px auto;
}
 
h1 {
  font: 40px/200px Helvetica, sans-serif;
  text-align: center;
}
<div class="container">
  <h1>I'm centered!</h1>
  </div>

option 6 (IMO the best)

using background image positioning

.container {
  height: 300px;
  width: 300px;
  margin: 150px auto;
  background: #eee url(http://lorempixum.com/100/100/nature/4) no-repeat center;
}
<div class="container"></div>

So, as you can see, there’s literally LOADS of ways to achieve this with just a few lines of code.

1

solved Centering image on full page with CSS [closed]