我前几天刚刚学习了 HTML&CSS,通过观看视频和阅读 W3C 中的相关教程。所以可能我错过了一些重要的点。
我想用css做一个渐变背景动画,下面是我的css和html代码:
body{
margin: 0;
background: linear-gradient(132deg,#ec5218,#1665c1);
background-size: 400% 400%;
animation: BackgroundGradient 30s ease infinite;
}
@keyframes BackgroundGradient{
0%{background-position: 0% 50%;}
50%{background-position: 100% 50%;}
100%{background-position: 0% 50%;}
}
h1{
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
}
<!doctype html>
<html>
<head>
<title>Gradiendt Background</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>There is a gradient background.</h1>
</body>
</html>
当我运行代码时,我得到的是白色背景而不是线性渐变背景。但是如果我在 body 元素中将背景属性设置为单一颜色,如蓝色,它确实有效。或者我设置边距属性设置为非零值,比如 1px,我会得到我想要的正确线性渐变背景。所以也许我真的很想念某事。
谁能给我一些提示?我将不胜感激。
最佳答案
Body
没有高度,因为 child 通过 position:absolute
离开了流程。因此,当您尝试调整大小时,400% 的无高度会给出 0 高度的背景
您可以安全地将 min-height:100vh
设置为 body
,以覆盖视口(viewport),即使背景设置为 HTML,它也会显示。
否则,如果 html
没有背景定义,任何 min-height
值都足以覆盖视口(viewport)。
参见 https://www.w3.org/TR/css3-background/#special-backgrounds了解涉及 html
和/或 body
时 background
的行为。
3.11.2. The Canvas Background and the HTML Element
For documents whose root element is an HTML HTML element [HTML401] or an XHTML html element [XHTML11]: if the computed value of ‘background-image’ on the root element is ‘none’ and its ‘background-color’ is ‘transparent’, user agents must instead propagate the computed values of the background properties from that element's first HTML BODY or XHTML body child element. The used values of that BODY element's background properties are their initial values, and the propagated values are treated as if they were specified on the root element. It is recommended that authors of HTML documents specify the canvas background for the BODY element rather than the HTML element.
body{
margin: 0;
background: linear-gradient(132deg,#ec5218,#1665c1);
background-size: 400% 400%;
animation: BackgroundGradient 30s ease infinite;
min-height:100vh;
}
@keyframes BackgroundGradient{
0%{background-position: 0% 50%;}
50%{background-position: 100% 50%;}
100%{background-position: 0% 50%;}
}
h1{
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
}
<!doctype html>
<html>
<head>
<title>Gradiendt Background</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>There is a gradient background.</h1>
</body>
</html>
关于html - 当我在 body 元素中将 margin 属性设置为零时,我得到了错误的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45129338/