2013-10-01 58 views
1

我想要垂直拉伸並定位頁面中心的背景圖像。與中心對齊的垂直拉伸背景

我認爲這很簡單,但似乎我不能以任何方式居中。這裏是我的CSS代碼:

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; 
} 

你有任何想法如何,我可以有這樣的背景下心?它現在對齊到左邊。謝謝!

回答

2

這是你想要的。

它垂直延伸圖像並將其放置在中央。

jsFiddle here

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

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

另外,如果你想爲老版本瀏覽器的支持,請參閱本jsFiddle solution。它使用img標籤,而不是通過background-image設置圖像。

+1

不,不幸的是,這並不能保持原始圖像的寬高比。 這裏是我的原代碼: http://jsfiddle.net/4Ubju/ 我的背景圖像是1280×1024,我需要舒展它只有垂直,水平對齊,並保持其寬高比。艱難的問題:) – Alex

+1

@Alex如果你想垂直拉伸,你爲什麼希望保持寬高比?我想我不明白你想要什麼。 –

+0

也許我的英語不好。我想100%垂直和水平自動,從而保持縱橫比。對不起我的英語不好。 – Alex

0

試着這樣做: -

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

OR

在這種情況下,你需要刪除 「position: fixed;」:

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

你需要給一些固定寬度的身體或DIV。

希望這會有所幫助!

+0

我的圖像寬度爲1280px,但如果拉伸,則身體的「寬度」值是沒有用的,因爲它不會正確對齊。 – Alex

+0

如果我刪除「位置」,它不會再垂直拉伸。 – Alex