How to remove the stripes that appears when using

2019-01-09 19:12发布

This question already has an answer here:

When using linear-gradient CSS property, the background appears without stripes when using left and right as direction value. But when direction value is given as top or bottom, stripes appears in the background. Is there any way that we can remove the stripes?

Here is the code:

body {
  background: linear-gradient(to top, red, yellow);
}

2条回答
祖国的老花朵
2楼-- · 2019-01-09 19:48

You are facing a complex background propagation that you can read about here. I will try to explain it with simple words.

Your body has a height equal to 0; thus the background won't be visible on it but by default it has 8px of margin which create a height of 8px on the html element.


Why not 16px of height (8px for top + 8px for bottom)?

Since the height of body is 0 we are facing a margin collpasing and both margin will collapse into only one and we have a height of 8px.


Then we have a background propagation from body to html and the linear-gradient will cover the 8px height.

Finally, the background of the html is propagated to root element in order to cover the whole area which explain that the linear gradient is repeating each 8px.

body {
  background: linear-gradient(to top, red, yellow);
}

It's also repeated when using left or right direction but you won't see it visually which is logic since it's the same pattern:

body {
  background: linear-gradient(to right, red, yellow);
}


In order to avoid this behavior you can simply set height:100% to the html

html {
  height: 100%;
}

body {
  background: linear-gradient(to top, red, yellow);
}

查看更多
姐就是有狂的资本
3楼-- · 2019-01-09 19:51

That's because the calculated height of <body> is resulting from the height of its content. When smaller than viewport's height, the background will repeat itself:

body {
  background: linear-gradient(to top, red, yellow);
}

To make sure it stretches itself (and the background gradient) across the entire height of the viewport, you need to give <body> a min-height equal with viewport's 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;
}

As @TemaniAfif pointed out in comments, the technical reason for the above is: there is a difference between the root element, which covers the entire viewport and inherits its background from <body>, and the <body> element, which, as specified, can be smaller than the viewport. As per W3C Recommendation:

The background of the root element becomes the background of the canvas and covers the entire canvas, anchored (for 'background-position') at the same point as it would be if it was painted only for the root element itself. The root element does not paint this background again.

查看更多
登录 后发表回答