使用纯CSS实现噪点效果

520 阅读3分钟

噪点是一种非常流行的设计元素,可以为网站或应用程序添加独特的视觉效果。

使用伪元素和背景图片

第一种实现噪点效果的方法是使用伪元素和背景图片。我们可以使用CSS中的:before和:after伪元素来添加噪点,并使用background-image属性将噪点图像设置为背景。然后,我们可以使用CSS filter属性对图像进行模糊处理,以达到噪点效果。

.noise {
  position: relative;
  background-color: #fff;
}

.noise::before,
.noise::after {
  content: "";
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url("noise.png");
  pointer-events: none;
  z-index: -1;
}

.noise::before {
  opacity: .2;
  filter: blur(4px);
}

.noise::after {
  opacity: .4;
  filter: blur(8px);
}

在这个例子中,我们首先定义了一个带有白色背景的.noise类,并使用:relative定位。 然后,我们使用:before和:after伪元素添加两个噪点层,并使用background-image属性将噪点图像设置为背景。 最后,我们使用CSS filter属性对图像进行模糊处理,并将不透明度设置为相应的值。

使用线性渐变和伪元素

第二种实现噪点效果的方法是使用线性渐变和伪元素。 我们可以使用CSS中的:before和:after伪元素来添加两个噪点层,并使用linear-gradient函数将其设置为线性渐变。 然后,我们可以使用mix-blend-mode属性将噪点混合到容器中。

.noise {
  position: relative;
  background-color: #fff;
}

.noise::before,
.noise::after {
  content: "";
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: -1;
}

.noise::before {
  background: linear-gradient(135deg, #000 25%, transparent 25%, transparent 50%, #000 50%, #000 75%, transparent 75%, transparent);
  mix-blend-mode: difference;
}

.noise::after {
  background: linear-gradient(45deg, #000 25%, transparent 25%, transparent 50%, #000 50%, #000 75%, transparent 75%, transparent);
  mix-blend-mode: exclusion;
}

在这个例子中,我们首先定义了一个带有白色背景的.noise类,并使用:relative定位。 然后,我们使用:before和:after伪元素添加两个噪点层,并使用linear-gradient函数将其设置为线性渐变。 最后,我们使用mix-blend-mode属性将噪点混合到容器中。

使用CSS伪随机数和背景图片

第三种实现噪点效果的方法是使用CSS伪随机数和背景图片。我们可以使用CSS中的calc()和random()函数来生成伪随机数,并使用:root选择器将其定义为CSS变量。然后,我们可以使用CSS var()函数将CSS变量应用于噪点图像,以达到噪点效果。

:root {
  --noise-color: #000;
}

.noise {
  position: relative;
  background-color: #fff;
}

.noise::before,
.noise::after {
  content: "";
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: -1;
  background-image: url("noise.png");
  background-repeat: repeat;
}

.noise::before {
  opacity: .2;
  filter: blur(4px);
}

.noise::after {
  opacity: .4;
  filter: blur(8px);
  background-color: var(--noise-color);
  mix-blend-mode: multiply;
}

.noise::after {
  background-image:
    repeating-linear-gradient(
      transparent 0,
      transparent calc(1% + 1px),
      var(--noise-color) calc(1% + 1px),
      var(--noise-color) calc(2% + 1px)
    ),
    url("noise.png");
}

在这个例子中,我们首先使用calc()和random()函数生成CSS伪随机数,并使用:root选择器将其定义为CSS变量。 然后,我们使用var()函数将CSS变量应用于噪点图像,并使用repeating-linear-gradient函数将其设置为线性渐变。 最后,我们使用mix-blend-mode属性将噪点混合到容器中。

总结

在本文中,我们介绍了三种使用纯CSS实现噪点效果的方法。 无论您是选择使用伪元素和背景图片、线性渐变和伪元素,还是CSS伪随机数和背景图片,这些技巧都可以快速轻松地为您的网站或应用程序添加独特的视觉效果。 无论您是设计师还是开发人员,都可以从这些技巧中受益,并实现出色的设计效果。