使用线性渐变CSS属性时,使用左右作为方向值时,背景显示无条纹。但是当方向值为顶部或底部时,条纹会出现在背景中。有什么方法可以删除条纹吗?
这是代码:
body {
background: linear-gradient(to top, red, yellow);
}
你正面临一个复杂的背景传播,你可以阅读有关here。我将尝试用简单的词语来解释它。
你的body
的高度等于0;因此背景将不会在其上可见,但默认情况下它具有8px
的边距,在8px
元素上创建html
的高度。
为什么不是16px的高度(顶部为8px,底部为8px)?
由于身体的高度为0,我们面对的是margin collpasing,两个边缘都会折叠成一个,我们的高度为8px。
然后我们有从body
到html
的背景传播,linear-gradient
将覆盖8px的高度。
最后,html的背景传播到canvas元素以覆盖整个区域,这解释了为什么线性渐变重复每个8px
。
body {
background: linear-gradient(to top, red, yellow);
}
当使用向左或向右方向时也会重复这种情况但你不会在视觉上看到它是合乎逻辑的,因为它是相同的模式:
body {
background: linear-gradient(to right, red, yellow);
}
你也可以删除重复,你会看到它只覆盖8px
body {
background: linear-gradient(to right, red, yellow) no-repeat;
}
为了避免这种行为,你可以简单地将height:100%
(或min-height:100%
)设置为html
html {
height: 100%;
}
body {
background: linear-gradient(to top, red, yellow);
}
它也适用于no-repeat
,因为默认情况下,linear-gradient
将覆盖整个:
html {
min-height: 100%;
}
body {
background: linear-gradient(to top, red, yellow) no-repeat;
}
这是因为<body>
的计算高度是由其内容的高度产生的。当小于视口的高度时,背景将重复:
body {
background: linear-gradient(to top, red, yellow);
}
为了确保它在视口的整个高度上伸展自身(和背景渐变),你需要给<body>
一个与视口高度相等的min-height
(100vw
):
body {
background: linear-gradient(to top, red, yellow);
min-height: 100vh;
}
body {
background: linear-gradient(to top, red, yellow);
min-height: 100vh;
margin: 0;
}
正如@TemaniAfif在评论中指出的那样,上面的技术原因是:根元素(覆盖整个视口并从<body>
继承其背景)与<body>
元素之间存在差异,如规定的那样,它可以更小比视口。根据W3C Recommendation:
根元素的背景成为画布的背景并覆盖整个画布,锚定(对于“背景位置”)与在仅为根元素本身绘制时相同的点。根元素不会再次绘制此背景。