2011-09-15 119 views
7

我有一个html页面,需要扩大宽度和高度,所以需要能够上下左右滚动,但我似乎无法获得css渐变重复 - x并向下留下纯色。CSS背景渐变重复问题

精简代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-type" content="text/html; charset=utf-8"> 
<style type="text/css" media="screen"> 
    html { 
     height: 100%; 
     background-color: #366fcd; } 
    body { 
     margin: 0; 
     height: 100%; 
     width: 100%; 
     background-color: #366fcd; 
     background: -moz-linear-gradient(center top, #316494 0%,#366fcd 100%); 
     background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #316494),color-stop(1, #366fcd)); 
     background-repeat: repeat-x; 
    } 
    div#TheElement { 
     position: absolute; 
     width: 100px; 
     height: 100px; 
     background-color: #fff; 
     left: 2000px; 
     top: 2000px; 
    }  
</style>  
</head> 
<body> 
    <div id="TheElement">   
    </div> 
</body> 
</html> 

这将运行渐变成纯色(#366fcd)当您向下滚动,但是当你向右滚动,渐变停止,您将看到纯色也有。 See example

如果我删除background-color:#366fcd; } from html元素,然后如预期的那样沿x轴重复渐变,但向下滚动时,渐变停止并出现白色。 See example

我知道我总是可以使用背景图片,但宁愿让CSS工作。

哦,是的,这是在OSX Lion的Chrome和FF测试。

安东尼

回答

17

所有你需要的是background-attachment财产。有了这个属性,你可以在身体完全填充屏幕高度的时候修复身体的背景。

background-attachment:fixed; 
height:100%; 

看这里 http://jsfiddle.net/mohsen/TanzY/

这里我举的例子就是你们的榜样固定:http://jsbin.com/ileqid/4

我删除background-repeat财产,也改变了颜色更加直观。

如果你想要你的背景卷轴,那么你需要设置the background-attachmentscroll。只有滚动条才会发生,如果您的内容较大,则在this例如,我将主体标记height设置为3000px

+0

你的固定JSBin例子似乎并没有在Mac上的Chrome 13的工作。当我滚动到右侧时,渐变背景仍然消失。 –

+0

我修正了这个问题,这是因为OP为CSS标签设置了CSS。 – Mohsen

+0

啊哈!我认为这可能是这样的。好工作。 –

2

将您的渐变应用于html标记。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
    <head> 
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"> 
    <style type="text/css" media="screen"> 
     html, body {    
      width:100%; 
      height:100%; 
      margin:0; 
      padding:0;}   
     html { 
      background:red -moz-linear-gradient(center top, #316494 0%,red 100%) repeat-x; 
      background:red -webkit-gradient(linear, left top, left bottom, color-stop(0, #316494),color-stop(1, red)) repeat-x; 
     } 
     div#TheElement { 
      position: absolute; 
      width: 100px; 
      height: 100px; 
      background-color: #fff; 
      left: 2000px; 
      top: 2000px; 
      border:1px solid #000; 
     }  
    </style>  
    </head> 
    <body> 
     <div id="TheElement">   
     </div> 
    </body> 
</html> 

经测试,在FF6,铬13和Safari 5