Sha
Sha

Reputation: 1974

Making background image responsive in CSS

I was trying to create a responsive website from scratch without using any frameworks like bootstrap. i had a banner in my website for which i had set background image as follows

<body>
    <div id="pagewrap">
        <div class="test">
            <div class="headers">
                <div class="logo">
                    <a href="#"><img src="images/logo.png" alt="Site Logo"/></a>
                </div><!--logo-->
                <div class="nav"></div><!--nav-->
                <div class="slider_content"></div><!--slider_content-->
            </div><!--header-->
        </div>
    </div><!--pagewrap-->
</body>
.headers {
    background-image:url(images/banner.png);
    background-repeat:no-repeat;
    background-size:cover;
    background-position:center;
    width:100%;
}

When I apply height to the div headers image gets displayed but it is taking the same height in mobile devices too which doesn't look good. How do I make this responsive so that the background image scales according to the device resolution.

Upvotes: 1

Views: 843

Answers (3)

user4563161
user4563161

Reputation:

Try applying padding percentages instead of a fixed height.

So padding-bottom:50%; and change cover to background-size:100% auto;

let me know how it goes I think this is how I got round it before.

Upvotes: 1

stanze
stanze

Reputation: 2480

Might this will help you, Demo

$( window ).resize(function() {
  var imgHeight = $( window ).height(),
      imgWidth = $( window ).width();
    $('.headers').css({
        height: imgHeight,
        width: imgWidth
    });
});

Upvotes: 1

moeses
moeses

Reputation: 507

Have you tried to work with percentage values? Something like height 100% Or you can experiment with the vh-attribute. but when you want to work with vh, make sure you're using jQuery too because of the browser-support:

var viewHeight = $( window ).height();
  $('.element').css('height', viewHeight);

Upvotes: 0

Related Questions