Skip to content Skip to sidebar Skip to footer

Keep Image Centered

I have this simple html: So far i centered the image correctly as long as the window is not small

Solution 1:

Try using it as a background-image. CSS:

.bg {
    background-image:url('http://i1.ytimg.com/vi/XWGszmviDpA/maxresdefault.jpg');
    width: auto;
    height: 100%;
    position: fixed;
    left:0;
    right:0;
    margin:0 auto;   
    width:70%; //Custom dimension
    background-position:center;
    background-size:cover; 
}

Demo: http://jsfiddle.net/lotusgodkk/67jDp/2/

Solution 2:

Try setting the image as the background of a div instead of an img tag

http://jsfiddle.net/CeVwN/1/

.bg {
    background-image:url('http://i1.ytimg.com/vi/XWGszmviDpA/maxresdefault.jpg');
    background-position:center;
    background-size: auto 100%;
    background-repeat: no-repeat;
    width: auto;
    height: 100%;
    position: fixed;
    left:0;
    right:0;
    margin:0 auto;
}

Solution 3:

You can use this with little javascript

css :

img.bg {
    height: 100%;
    position: fixed;
    left:50%;
}

JS :

var i = $('img');
var w = i.width();

i.css({marginLeft: -w/2});

$( window ).resize(function() {
    i.css({marginLeft: -w/2});
});

DEMO : http://jsfiddle.net/67jDp/4/

Solution 4:

Set width to 100% to get always the container's width. Then, set height to auto to allow the ratio:

img.bg {
    width: 100%;
    height: auto;
    position: fixed;
    left:0;
    right:0;
    margin:0 auto;   
}

Remember to set a max-width to stop expanding when necessary.

Post a Comment for "Keep Image Centered"