2013-02-05 122 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。没有它,它只会将图像的左上角像素放在中央,而不是整个图像的美丽。