how can i stretch my background image ?

Dani AI

Generated

's "fixed element behind content" trick is a good, compatible solution for very old browsers. For modern browsers the simplest, least-markup approach is CSS3's background-size. It scales the page background with a single rule and preserves aspect ratio when desired.

/* simplest full-viewport background for modern browsers */
body {
  margin: 0;
  background: url('background.jpg') center center no-repeat fixed;
  -webkit-background-size: cover;
  background-size: cover;
}

background-size: cover fills the viewport while keeping the image's aspect ratio (it will crop where necessary). background-size: contain fits the whole image inside the viewport (letterboxing), and background-size: 100% 100% stretches and will distort the image.

Practical notes and gotchas:

  • Mobile: many mobile browsers ignore background-attachment: fixed for performance, so the fixed/parallax effect may not appear on iOS; the positioned-element approach from can be used as a fallback where fixed is required.
  • Performance: use appropriately sized images (and modern formats like WebP/AVIF) and swap files with CSS media queries for narrow screens to save bandwidth.
  • Retina: provide higher-resolution assets via media queries (device-pixel-ratio or resolution) so large displays stay crisp.
  • If responsive source selection is needed (different files at different widths), use an actual <img> or <picture> placed behind content with object-fit: cover and srcset so the browser can pick the best file.

For legacy IE (<9) support, the positioned background element method (as demonstrated by ) or conditional CSS is the practical fallback. Test across aspect ratios to make sure important parts of the image are not unintentionally cropped.

Here is one way to do it. I picked it up sometime ago from somewhere (I don't remember). Hope it serves your purpose.

<style type="text/css">
/* this actually pulls the page to the full capacity of the viewing area */
html {
height:100%;
}
body {
height:100%; 
margin:0; 
padding:0;
}
/* pulls the background image to full capacity of the viewing area */
#bg {
position:fixed; 
top:0; left:0;
 width:100%;
 height:100%;
}
/* places the content ontop of the background image */
#content {
position:relative;
 z-index:1;
}
</style>
<!--[if IE 6]>
<style type="text/css">
/*  css fixes for IE browsers */
html {
overflow-y:hidden;}
body {
overflow-y:auto;}
#bg {
position:absolute;
 z-index:-1;
}
#content {
position:static;
}
</style>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.