I'm trying to get a linear gradient working as the background of my page. The gradient is not showing at all, and the background remains white. Here's the minimal code to reproduce the issue:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <meta charset="utf-8">
    <style type="text/css">
    body
    {
        width:100%;
        margin-left:-50%;
        position:absolute;
        left:50%;
        background: rgb(0, 0, 0);
        background: -moz-linear-gradient(270deg, rgb(0, 0, 0) 1%, rgb(21, 126, 250) 99%);
        background: -webkit-linear-gradient(270deg, rgb(0, 0, 0) 1%, rgb(21, 126, 250) 99%);
        background: -o-linear-gradient(270deg, rgb(0, 0, 0) 1%, rgb(21, 126, 250) 99%);
        background: -ms-linear-gradient(270deg, rgb(0, 0, 0) 1%, rgb(21, 126, 250) 99%);
        background: linear-gradient(0deg, rgb(0, 0, 0) 1%, rgb(21, 126, 250) 99%);

    }
    </style>
</head>
<body>

    This is a test and a bad one at that.

</body>
</html>

Now if I remove the position:absolute, the gradient works. What am I doing wrong? I need to have that position:absolute, so what can I do?

Edit: tried this in Chrome and Firefox.

有帮助吗?

解决方案

If you do not set an html background, body's background is applyed to HTML.

Since body is in absolute, it has a 0 size for HTML and it doesn't trigger anything for HTML layout.

try to apply:html {height:100%;} and see what it does : http://codepen.io/anon/pen/JGApK

其他提示

that's easy

you just need to add background-attachment: fixed !important; to body and/or height:100% to html.

made a fiddle: http://jsfiddle.net/filever10/NA7a6/

Though either option switches the background from body to html, so it may be a better solution to put the background on html directly, since it's going to go there regardless.

like this: http://jsfiddle.net/filever10/nRLNb/

You can just add position: relative; to the parent element, in your case its the html tag.

html{
  position: relative;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top