简体   繁体   中英

Responsive image with div by css background-image

I have found there are similar questions here, like Responsive CSS background images .

This solution didn't work for me unless I have set the exact height of the image for that div. Firstly, if I don't set its height, the image won't be shown as the height of div will be zero. Secondly, if I set the height for it, it won't be responsive to the browser width. Like if I widen the browser, I expected the image will scale up responsively to fit with the width. But if I use height:100%, the image won't be shown again.

I want it to be: When I adjust the browser width, the image width and height will be scaled up/down responsively with using css background-image attribute.

I guess it is related to some fundamental css tricks but I am not really good at it. Could anyone suggest me some solutions on it? Thank you so much!

 .top-banner{ height:100%; } @media (min-width:768px) { .top-banner { background-image: url('http://everetttheatre.com/wp-content/uploads/2016/03/toy-story-banner.jpg'); background-repeat: no-repeat; background-size: contain; background-position: center; } } @media (max-width:767px) { .top-banner { background-image: url('https://i.pinimg.com/originals/31/de/36/31de3624c128d5748039ae9523223eb5.jpg'); background-repeat: no-repeat; background-size: contain; background-position: center; } } 
 <div class="top-banner"> </div> 

Height in percentage wont work unless any of the parent element has height in pixel.

My suggestion is to use img tag instead of background-image to make it responsive.

But If you can only use div with background image, then you have change the height of the div on window resize event using javascript.

Like if image is 4:3 ratio, the code will something like below :

<body onresize="resizeFunction()">
   <style>
    .imgBackground {
       width : 100%;
       background : your image link;
       background-size : 100%;
    }
   </style>
   <div class="imgBackground"></div>
   <script>
       function resizeFunction() {
         var widthOfDiv = $('.imgBackground').width();
         var heightOfDiv = width/1.33;
         $('.imgBackground').height(heightOfDiv);
      }
   </script>
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM