admin管理员组

文章数量:1327805

My website's background is a huge image that covers the whole webpage, how can I make it so that, we detect user's screen size and change the background image accordingly?

Say for example, my background image is 1x1px, if user screen is 2x2px (this is just an example, nobody has this kind of small screen), I want stretch my background to fit 2x2. If user screen is say, 0.5x0.6px, then I want my background to be shown only its 0.5x0.6px part, not the whole 1x1px.

My website's background is a huge image that covers the whole webpage, how can I make it so that, we detect user's screen size and change the background image accordingly?

Say for example, my background image is 1x1px, if user screen is 2x2px (this is just an example, nobody has this kind of small screen), I want stretch my background to fit 2x2. If user screen is say, 0.5x0.6px, then I want my background to be shown only its 0.5x0.6px part, not the whole 1x1px.

Share Improve this question asked Aug 15, 2011 at 15:20 HenryHenry 2774 silver badges9 bronze badges 1
  • Did I understand the last sentence correctly: if the screen is smaller than the picture it should not scale down but be shown in original size but cropped? Should the image retain its proportions? – JJJ Commented Aug 15, 2011 at 15:27
Add a ment  | 

4 Answers 4

Reset to default 3

Use an image tag as the background give it a 100% for width and height, and set it behind all of the content with z-index give it absolute positioning and set its top and left where you need it to be.

<img src="yourimage" width="100%" height="100%" style="z-index:0"/>

Live Demo

In CSS3, we have a new property called background-size:

body {
    background-size: 100%;
}

looking for this?

<div style="width:100%; z-index:0; height:100%; background: url(1pximage.gif)"></div>

You can detect the users screen size and do it, also you can attach a event handler to do the same when the window size is modified.

$(function(){

   $(window).resize(function(){

      var windowW = $(window).width();
      var windowH = $(window).height();

      //Using above variables you can deside the size of the background image to be set 
   }).resize();//Trigger the resize event on page load.
});

本文标签: javascriptbackground image change with screen sizeStack Overflow