Skip to content Skip to sidebar Skip to footer

Responsive Div Scaling Within "background-size: Contain" Image

UPDATED 01/01/15 Problem: I have a centered background image that is scaling with background-size: contain. I would like to have DIVs (for links, etc.) that overlay on the backgrou

Solution 1:

I'm actually somewhat close, I think. The only problem I am still having is when I make the browser window very narrow vertically, the DIVs shift down and don't stay positioned properly.

Updated Fiddle here.

I'm resorting to JavaScript to get the actual background image size, then calculating the DIV's size and position based on those results.

$(window).on("resize", function() {

    var width = $('.bg').width();
    var height = $('.bg').height();

    var imgWidth = width > height ? 350/325 * height : width;
    var imgHeight = height > width ? 325/350 * width : height;
    var imgTop; //need to do calculations on this

    $('.navbar').css({
        'width': imgWidth,
        'height': imgHeight * .15,
    });

});

Solution 2:

Rather than use background-size: contain, if you can use background-size: cover (without the image degrading too much), then the background image will fill the container completely. Since the percentage positions are relative to the container, they are now also relative to the image. So they now stay much closer to their original positions over the image.

Solution 3:

Working Fiddle

By the use background-size: cover; you can achieve that.

html, body {
    background: url("https://placekitten.com/350/325") no-repeat scroll center center / cover #000;
    height: 100%;
    margin: 0 auto;
    min-width: 325px;
    overflow-x: hidden;
    width: 100%;
}

Check this out. Perfect Full Page Background Image

Another solution can be background-size: 100% 100%;

Working Fiddle

Post a Comment for "Responsive Div Scaling Within "background-size: Contain" Image"