dragoweb
dragoweb

Reputation: 731

vertically centered image in div

I try to vertically center an image in the middle of the body but nothing seems to work. I've tried different tricks found here (height 100%, table-cell, position:relative...), but with no luck until now. My code is html:

 <div id="container">
   <div id="header">Header</div>
   <div id="body">
       <div class="image"></div>
   </div>
   <div id="footer">Footer</div>
 </div>

CSS:

html,
body {
   margin:0;
   padding:0;
   height:100%;
}
#container {
   min-height:100%;
   position:relative;
}
#header {
   background:#ccc;
   padding:10px;
}
#body {
   padding:10px;
   padding-bottom:60px;
}
.image {
    background: url("http://lorempixel.com/300/200/nature/") no-repeat center;
    height: 200px;
    width: 100%;
}
#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:60px;
   background:#ccc;
}

I made a fiddle here: http://jsfiddle.net/dragoeco/hjcz6j0r/1/ I looking for a working solution with IE8+ so maybe there is a jQuery way to do that job? What is important for me is to keep the footer at the bottom of the viewport so that's why I used a obsolute position for footer. Thanks.

Upvotes: 0

Views: 131

Answers (3)

Sergey6116
Sergey6116

Reputation: 124

Add this:

.image{
    position: absolute;
    top: 50%;
    margin-top: -100px;
}

It works everywhere (except IE6-7, position relative may be needed there). You can do the same for horizontal centering.

Here is the fiddle: http://jsfiddle.net/hjcz6j0r/7/

Upvotes: 0

KevinRyan
KevinRyan

Reputation: 51

I had success with the following CSS:

html,
body {
   margin:0;
   padding:0;
   height:100%;
}
#container {
   min-height:100%;
   position:relative;
}
#header {
   background:#ccc;
   padding:10px;
   position: relative;
}
#body {
   padding:10px;
   padding-bottom:60px;
    position: relative;
}
.image {
    background: url("http://lorempixel.com/300/200/nature/") no-repeat center ;
    position: absolute;
    height: 200px;
    width: 100%;
    top: 50%;
}
#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:60px;
   background:#ccc;
}

Source: http://www.w3.org/Style/Examples/007/center.en.html#vertical

Upvotes: 1

mpgn
mpgn

Reputation: 7251

Something like this maybe :

LIVE EXAMPLE

html, body {
    height: 100%;
}
#container {
    height: 100%;
    width: 100%;
    display: table;
    margin-top:-60px; //height of the footer
}
#body {
    display: table-cell;
    height: 100%;
    vertical-align: middle;

}

.image {
    background: url("http://lorempixel.com/300/200/nature/") no-repeat center;
    height:200px;
}

#header {
   background:#ccc;
   padding:10px;
}

#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:60px;
   background:#ccc;
}

Upvotes: 3

Related Questions