webrebuild.org第四届年会——金秋四城联动

固宽背景图居中错位的问题

在 IE/FF/OP/Safari/chrom 中运行下面代码,然后将页面收缩至小于980px

html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="zh-CN" />
<title>test</title>
<style type="text/css" >
body {background:url(http://www.vfresh.org/wp-content/uploads/2009/03/test.gif) top center no-repeat;}
#trunk {width:980px;height:100px;margin:0 auto;}
</style>
</head>
<body>
<div id="trunk">
	testtest!~~~~~~~~~
</div>
</body>
</html>

会发现在FF/OP下背景图错位了,而IE/chrom/safari下是正常的。

可以使用以下hack解决这个问题:

css
body {display:table;width:100%}
html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="zh-CN" />
<title>test</title>
<style type="text/css" >
body {background:url(http://www.vfresh.org/wp-content/uploads/2009/03/test.gif) top center no-repeat;display:table;width:100%}
#trunk {width:980px;height:100px;margin:0 auto;}
</style>
</head>
<body>
<div id="trunk">
	testtest!~~~~~~~~~
</div>
</body>
</html>

这个bug触发的条件:
1.主容器未定宽度或宽度为100%
2.主容器背景属性符合:background-repeat:no-repeat;background-position:center 0;(不平铺、横向居中)
3.子容器有定义宽度

原因:FF/OP是将body的总宽度定为了当前浏览器的宽度
也就是说,当浏览器缩小至800px的时候,FF/OP将body的宽度设为800px,再将body的背景图按照宽度800px居中放置,而body的子容器#trunk是980px,冲破了body,这样就导致了错位的问题。

这个问题在所有未定宽度或宽度为100%的容器内都有发生。
对于非body元素,我们可以使用以下方式修正:

css
div {min-width:980px;}

相关阅读

  1. 小技巧:带分隔线左右布局的实现
  2. 合理隐藏文字
  3. IE 6实现min/max-height/width
  4. HTML默认样式
  5. 纯CSS的图片展示效果