Domanda

I want to have a background image stretched vertically and positioned center of page.

I thought it would be simple, but it seems I cannot center it in any way. Here is my CSS code:

HTML

<div id="background">
    <img src="bkg.jpg" class="stretch" />
</div>

CSS

#background {
    width: auto;
    height: 100%;
    position: fixed;
    z-index: -999;
}

.stretch {
    width: auto;
    height: 100%;
}

body {
    margin-left: 0px;
    margin-top: 0px;
    margin-right: 0px;
    margin-bottom: 0px;
    background-color: #525252;
}

Do you have any ideas how I can have this background centered? It's now aligned to the left. Thanks!

È stato utile?

Soluzione

This works how you want it.

It stretches the image vertically and positions it in the center.

jsFiddle here

body {
    margin:0px;
    background-color: #525252;
}

#background {
    width: 100%;
    height: 100%;
    position: fixed;
    background: url('bk.jpg') center / auto 100% no-repeat;
}

Alternatively, if you want support for older browsers, see this jsFiddle solution. It uses the img tag as opposed to setting the image via background-image.

Altri suggerimenti

Try doing this:-

body {
    margin: 0px auto;
    width:1000px;
    background-color: #525252;
}

OR

In this case you need to remove "position: fixed;":

#background {
    height: 100%;
    z-index: -999;
    margin: 0px auto;
    width:1000px;
}

You need to give some fixed width to body or the DIV.

Hope this helps!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top