简体   繁体   中英

Centering CSS background image

The website I'm working on, Tamsnails.com , is just about done, but it has one issue that I've been bothered with for a while now. The background image of the store will simply not stretch to the full screen of my high resolution work laptop. I've tried a lot of things over the last couple of months, a lot of which I forget, but

I remember at first, I had it as an actual css background-img

then, I had

<head>
<body id="theBody">
<div id="backgroundImageWrapper" style="height: 100%; width: 100%; z-index: 0; position: absolute;">
<img id="mainBackgrond" src="background_image.JPG">
</div>

with mainbackground style

#mainBackgrond {
    height: 100%;
    left: 0;
    position: absolute;
    top: 0;
    width: 100%;
    z-index: -1;
}

Now, I have

<body id="theBody">
<img id="mainBackgrond" src="background_image.JPG">
<div id="wrapper">

with style

#mainBackgrond {
    height: 50em;
    left: 0;
    position: absolute;
    top: 0;
    width: 100%;
    z-index: -1;
}

because this at least looks good on my home laptop.

Yes, I know I spelled 'mainBackgrond' wrong.. bear with me here!

If the issue is that the image doesn't stretch to the bottom of the window (which is what I'm seeing in Chrome) then change the height: 50em on your #mainBackgrond style to:

height: 100%;

I don't think you can, unless you want to use HTML 5.

See: css scaled background image if that's acceptable to you.

Edit: FYI, using "Height: 100%" stretches to 100% of the content height, not the window.

You might want to take a look at this ( or other similar jquery plugins )

http://srobbin.com/blog/jquery-plugins/jquery-backstretch/#demo - Quite simple to use and it stretches the background image fully without risking the aspect ratio.

Try to remove the height property, this way it will maintain the aspect ratio and stretch all the way across the screen, if this is the intent.

#mainBackgrond {
  position: fixed;
  z-index: -1;
  width: 100%;
  left: 0px;
  top: 0px;
  background: url(/background_image.JPG) no-repeat center center fixed;
}

The background image itself is huge, and makes initial load time very slow, you should consider compressing it more or resizing.

also have a look at css media query a nice way to show different size background images for visitors with smaller screens that might not even have the resolution to see the background.

@media screen and (max-device-width: 480px) {
  .column {
    float: none;
  }
}

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