2013-02-05 121 views
1

我需要顯示其下有敷設渠道頁簡單的圖像,讓我們說800x700px &我想這個形象出現在頁面的中心垂直地&水平,垂直和水平居中對齊圖像的網頁

我嘗試了不同的方法,但沒有奏效。下面的示例html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<style type="text/css"> 

html, body { height: 100%; width: 100%; } 
body { position: relative; background-image:url('images/bg.jpg');background-repeat:repeat; } 
#mydiv { 
    position: absolute; 
    height: 100%; 
    width: 100%; 
    text-align:ceter; 
} 
</style> 
</head> 
<body> 
</body> 
</html> 

回答

6

查看本文由Chris Coyier在CSS-Tricks上查看。我認爲這可能有所幫助。幾天前我遇到了同樣的問題,他的回答對我很有幫助。

Centering an image horizontally and vertically

基本的想法是,如果你的形象有一組寬度和高度。你可以絕對地將它從左邊和上邊定位50%,然後做負邊界,等於寬度和高度的一半,使它回到死點。如果圖像沒有設置尺寸,它們是垂直居中放置圖像的其他方法。

+3

這是他需要在頁面中心顯示圖像的代碼。沒有其他的CSS需要:'#mydiv img {position:absolute;頂部:50%;剩下:50%; margin:-350px 0 0 -400px; }' – kleinfreund

+0

@kleinfreund正確 –

1

您沒有爲div設置ID,我編輯過,一旦完成,圖像將水平對齊。而且,mydiv不需要被定位爲「絕對」。

要垂直對齊圖片,不使用javascript的最佳解決方案是將img設置爲margin-top。

#mydiv { 
text-align: center; 
} 

#mydiv img { 
margin-top: 15%; 
} 
+0

這是行不通的 – Learning

+0

@KnowledgeSeeker請檢查這個,http://jsfiddle.net/7wKVE/。另外,你可以請分享你現在的確切代碼嗎? – KBN

6

無論長度如何,此CSS都可以使圖像居中。

.centered { 
    position: fixed; 
    top: 50%; 
    left: 50%; 
    /* bring your own prefixes */ 
    transform: translate(-50%, -50%); 
} 

祕密是在transform。沒有它,它只會將圖像的左上角像素放在中央,而不是整個圖像的美麗。