69

Is it possible to add noise to a gradient in CSS?

Here is my code for a radial gradient:

body {
    color: #575757;
    font: 14px/21px Arial, Helvetica, sans-serif;
    background-color: #2f3b4b;
    background: -moz-radial-gradient(center 45deg, circle closest-corner, #2f3b4b 0%, #3e4f63 100%);
    background: -webkit-gradient(radial, center center, 10, center center, 900, from(#2f3b4b), to(#3e4f63));
}

What would I add to that to have noise on top of it, to give it texture?

1
  • 1
    why you weren't add normal radial-gradient?
    – doğukan
    Jul 31, 2019 at 15:23

9 Answers 9

120

This is by far the most hassle free and best way to implement this. It is purely CSS and very very simple to do, no extra files - nothing. Ok, it's not the best way possible, but it works very well, very reliable (never failed when testing across very old browsers) and very fast to load.

Found it a few months ago, and used it ever since, simply copy and paste this code in to your CSS.

background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAMAAAAp4XiDAAAAUVBMVEWFhYWDg4N3d3dtbW17e3t1dXWBgYGHh4d5eXlzc3OLi4ubm5uVlZWPj4+NjY19fX2JiYl/f39ra2uRkZGZmZlpaWmXl5dvb29xcXGTk5NnZ2c8TV1mAAAAG3RSTlNAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAvEOwtAAAFVklEQVR4XpWWB67c2BUFb3g557T/hRo9/WUMZHlgr4Bg8Z4qQgQJlHI4A8SzFVrapvmTF9O7dmYRFZ60YiBhJRCgh1FYhiLAmdvX0CzTOpNE77ME0Zty/nWWzchDtiqrmQDeuv3powQ5ta2eN0FY0InkqDD73lT9c9lEzwUNqgFHs9VQce3TVClFCQrSTfOiYkVJQBmpbq2L6iZavPnAPcoU0dSw0SUTqz/GtrGuXfbyyBniKykOWQWGqwwMA7QiYAxi+IlPdqo+hYHnUt5ZPfnsHJyNiDtnpJyayNBkF6cWoYGAMY92U2hXHF/C1M8uP/ZtYdiuj26UdAdQQSXQErwSOMzt/XWRWAz5GuSBIkwG1H3FabJ2OsUOUhGC6tK4EMtJO0ttC6IBD3kM0ve0tJwMdSfjZo+EEISae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JpiKYkmW3tTg3ZQ9Jq+f8XN+A5eeUKHWvJWJ2sgJ1Sop+wwhqFVijqWaJhwtD8MNlSBeWNNWTa5Z5kPZw5+LbVT99wqTdx29lMUH4OIG/D86ruKEauBjvH5xy6um/Sfj7ei6UUVk4AIl3MyD4MSSTOFgSwsH/QJWaQ5as7ZcmgBZkzjjU1UrQ74ci1gWBCSGHtuV1H2mhSnO3Wp/3fEV5a+4wz//6qy8JxjZsmxxy5+4w9CDNJY09T072iKG0EnOS0arEYgXqYnXcYHwjTtUNAcMelOd4xpkoqiTYICWFq0JSiPfPDQdnt+4/wuqcXY47QILbgAAAABJRU5ErkJggg==);

Then add your background color

background-color:#0094d0;

Demo: JSFiddle

Source: https://coderwall.com/p/m-uwvg

6
  • What exactly happens in the url() part of the code? Is there a way to customize the granularity and other parameters? Oct 5, 2016 at 11:01
  • 1
    @tobias47n9e the data within in the URL part is just a small image. You could change that to any image URI data (google "convert image to URI). Note it is uri data you want or urL!
    – tim.baker
    Oct 5, 2016 at 11:26
  • Doesn't work with gradients since CSS gradients are technically background-image props (same as your data-uri which overwrites). Sep 2, 2017 at 4:51
  • 4
    @corysimmons That's incorrect. To use it with a gradient, simply append a comma and the gradient in the same background-image property.
    – Orbit
    Oct 1, 2017 at 17:30
  • 1
    What? You can set multiple background-image to the same element? So div { background-image: linear-gradient(to bottom, black, white), linear-gradient(to right, black, white) } should work?? Update: Holy snot, you're right. Beautiful! Nov 10, 2017 at 17:13
41

Creating Textures (Noise) Using SVG Filters & CSS Gradients

You want noise in your gradient? You're in luck!

Perlin noise is a type of gradient noise. The SVG standard specifies a filter primitive called <feTurbulence>, which implements the Perlin function. It allows the synthesis of artificial textures like clouds or marble—the noise you want.

Step 1: Define an SVG Graphic

Create a small SVG file called noise.svg.

<svg
  xmlns='http://www.w3.org/2000/svg'
  xmlns:xlink='http://www.w3.org/1999/xlink'
  width='300' height='300'>

    <filter id='n' x='0' y='0'>
            <feTurbulence
              type='fractalNoise'
              baseFrequency='0.75'
              stitchTiles='stitch'/>
    </filter>

    <rect width='300' height='300' fill='#fff'/>
    <rect width='300' height='300' filter="url(#n)" opacity='0.80'/>
</svg>

This graphic defines two rectangles. The first is filled with a solid color. The second is translucent with the noise filter applied. The second rectangle is overlayed on the first to provide a noise effect.

SVG Options

  1. Fist and most obvious is that you can change the dimensions of the graphic. However, the CSS background-repeat property can be used to fill an element, thus 300×300 should suffice.

  2. The filter's type attribute can be fractalNoise or turbulence, which specifies the filter function. Both provide a different visual, but in my opinion, the noise filter is a little more subtle.

  3. The filter's baseFrequency attribute can range from 0.5–0.9 to provide a course to fine texture, respectively. This range is visually optimal for either filter in my opinion.

  4. The first rectangle's fill can be changed to provide a different base color. Later, however, we essentially combine this color with a translucent CSS gradient, which also defines a color(s). So white is a good starting point here.

  5. The second rectangle's opacity can range from 0.2–0.9 to set the filter intensity, where a higher number increases the intensity.

At this point, you could tweak the aforementioned options, set this noise graphic as a background image via CSS, and call it a day. But if you want a gradient, like the OP, go to Step 2.

Step 2: Apply a CSS Gradient

Using the background-image property, you can set the SVG noise graphic as the background on any element and overlay a gradient. In this example, I'll apply the noise graphic to the entire body and overlay a linear gradient.

body {
    /* white to black linear noise gradient spanning from top to bottom */
    background:
      linear-gradient(rgba(255,255,255,.5), rgba(0,0,0,.5)),
      url('noise.svg');
}

The linear-gradient() function creates a pseudo image, which is stacked on top of noise.svg. The result is a translucent gradient with our noise showing through it.

CSS Options

  1. First, and most obvious, is that the defined gradient colors can be changed. However, if you want a solid color without a gradient, make the two end-point colors equal. The benefit is that you can use the same noise graphic with or without a gradient throughout a site or among projects.

  2. Multiple images, created with the *-gradient() functions, can be overlayed on the noise graphic and more than two color parameters and angles can be specified in a single gradient function to provide all kinds of cool visuals.

  3. The opacity of the gradient parameters—i.e. rgba() and hsla()—can be increased to intensify the defined color and reduce the noise level. Again, 0.2–0.9 is an ideal range.

Conclusion

This is a highly customizable and very light-weight (~400 bytes) solution that allows you to simply define noise of any color or gradient. Although there are several knobs to turn here, this is only the beginning. There are other SVG filter primitives, such as <feGaussianBlur> and <feColorMatrix>, which can provide additional results.

4
  • 3
    For an example of how I applied this technique to match a given gradient, see my answer to this question. Mar 5, 2018 at 13:20
  • 4
    Can you link to a demo? May 6, 2018 at 6:07
  • You can also apply the SVG filter directly to an element by using CSS, as in body {filter: url(#n)} for example.
    – Shikkediel
    Oct 10, 2020 at 3:22
  • @ClintPachl such a great solution! Thanks for this. Way more efficient than doing it with a canvas. For anyone one that want's to see a animated version I created an example in stackblitz stackblitz.com/edit/react-ts-xc2kyo
    – stwilz
    Sep 4, 2021 at 8:25
27

There's no current way in css to add 'noise' to a background.

An alternative solution would be to create a transparent noise png in your graphic editor. Then apply that graphic as a background to a <div>. You would then need to place that <div> over the entire area of the <body> which should then give an appearance of a gradient with noise.

4
  • 9
    Or use multiple background images, the upmost one being your noise PNG. Browsers supporting gradients often support those, too.
    – DanMan
    Oct 30, 2010 at 16:10
  • 5
    In my opinion, overlaying noise doesn't look as nice as real noise. It would be better if the noise overlay would be blended using a "multiply" mode, but CSS doesn't support that. But the alternative of using a huge image of a gradient with noise isn't perfect either, as images with noise don't compress very well... Feb 15, 2011 at 19:46
  • 1
    Can we do this with filters? Mar 27, 2017 at 20:25
  • 1
    For reference in 2020, as this is the top answer, see answers further down.
    – tim.baker
    May 21, 2020 at 20:52
21

For the sake of novelty, here is some pure CSS noise without using a data URI:

#box {
  width: 250px;
  aspect-ratio: 1;
  position: relative;
  background: 
    repeating-radial-gradient(closest-corner at 1% 21%, rgba(255,0,255,.5), rgba(0,255,255,.5), #000 1.7%), 
    repeating-radial-gradient(closest-corner at 51% 51%, #fff, #fff, rgba(0,255,0,1) 10%);
  background-size: 55px 10px;
}

#box::before {
  position: absolute;
  z-index: 1;
  inset: 0;
  background: 
    repeating-radial-gradient(closest-corner at 21% 21%, #fff, rgba(0,0,255,.5), rgb(3,0,255) 20%), 
    repeating-radial-gradient(closest-corner at 61% 21%, #fff, rgba(0,255,0,.5), rgb(3,0,255) 20%), 
    repeating-radial-gradient(closest-corner at 91% 51%, #fff, rgba(255,255,1,.5), rgb(055,255,255) 20%);
  background-size: 15px 13px, 12px 22px, 12px 22px;
  background-blend-mode: exclusion, normal;
  mix-blend-mode: exclusion;
  content: ''
}
<div id="box"></div>

Some more information about how this was created: http://jollo.org/LNT/public/css-noise.html

2
  • 2
    how does this work? just a bunch of gradients added and subtracted from one another? Jan 19, 2020 at 14:03
  • Statistics of colors (e.g. standard deviation of lightness) across rows or columns have spatial coherence at some but not all combinations of zoom levels (including 100%) and DPI settings. Zooming in a lot reveals patterns. Just saying for those who are curious about this.
    – root
    Jan 21 at 11:13
15

It's 2023, so here's my answer: the best option would be with a lightweight inline SVG filter and one CSS declaration... which includes the background gradient. No external files, no base64-ing anything. Plus it does a good job of preserving the non-grainy gradient as it doesn't mess up with its contrast or brightness.

The SVG filter would look as follows:

<svg width='0' height='0'>
  <filter id='grainy' x='0' y='0' width='100%' height='100%'>
    <feTurbulence type='fractalNoise' baseFrequency='.537'/>
    <feColorMatrix type='saturate' values='0'/>
    <feBlend in='SourceGraphic' mode='multiply'/>
  </filter>
</svg>

The CSS code would look as follows:

background: filter(radial-gradient(circle, red, tan), url(#grainy))

What's the catch?

Well, it doesn't really work anywhere at this point (early January 2023), though it should soon start working in Safari. Safari is the only browser to have implemented the filter() function, which allows us to only apply a filter on a background-image layer, without affecting the element's text content or descendants. Right now, even in Safari, it only works on url() images, though it should soon work on CSS gradients as well.

We can still do this and it works cross-browser:

background: radial-gradient(circle, mediumturquoise, darkslateblue);
filter: url(#grainy)

live demo

However, as mentioned above, this filter affects the entire element it's set on, including descendants and text content.

In order to avoid that, we need to move the background and filter declarations on a pseudo, absolutely positioned, behind its parent's content, covering the area of its entire parent - live demo.

This is easily doable and cross-browser, but it would still be nicer to have support for the filter() function, not use up a pseudo just for this and reduce the CSS needed for this to ~15% of what we have to write now with this workaround.

So here are the bug links for this in the other browsers:


One more thing: if you don't really need the graininess, it's just a nice to have visual enhancement, you could store the gradient in a --grad custom property and have:

div {
    --grad: radial-gradient(circle, mediumturquoise, darkslateblue);
    background: var(--grad);
    
    @supports (background: filter(conic-gradient(red, tan), blur(1px))) {
        background: filter(var(--grad), url(#grainy))
    }
}

For anyone interested, breaking down the SVG filter:

  • this svg only exists to contain the filter, it won't actually be used to display anything, so we zero its dimensions (and ideally also get it out of the flow with position: absolute in the CSS); no other attributes on it are necessary when it's inline (if you want to move it to an external file, you'll have to add xmlns='http://www.w3.org/2000/svg')

  • the filter obviously needs an idto be referenced, but by default, the filter effect will also spill (relevant for feTurbulence) outside the the element it's applied to by 10% in every direction (default values for x and y are -10% and for width and height are 120%), so we want to restrict it to just the element's area, from 0% to 100% along both axes (alternatively if you don't feel like setting all those attributes, I guess you could set clip-path: inset(0) in the CSS; note that overflow: hidden won't cut it as that only hides the element's content spilling outside its padding-box, but not graphical effects on the actual element, such as those produced by a filter)

  • first filter primitive creates a noise layer; I don't really understand how this works - there's this article which a lot of people have recommended, but it loses me once it goes from 1D to 2D; what I have noticed is that it's better to switch from the default type value (turbulence) to fractalNoise and that the smaller the baseFrequency value is, the finer the graininess of the noise is (also, don't use integers for this - use 7.01, but not 7)

  • second filter primitive completely desaturates its input (equivalent to the effect of grayscale(1) or saturate(0)); since we haven't explicitly specified an input, it defaults to using the result of the previous filter primitive - the noise layer; to do this, it switches from the default type for feColorMatrix (which is matrix) to saturate and sets values to 0 (if you have a good mental image of the HSL model/ bicone, you'll know that a saturation of 0% means we always have a grey; how light or how dark, that depends on the lightness, the 'L' in "HSL")

  • third and final filter primitive blends the desaturated noise with the element the filter is applied on; feBlend takes two inputs, one of which is set to 'SourceGraphic' (note those capitals matter!), while the other one defaults to using the result of the previous filter primitive; finally, the mode we use is multiply (this multiplies the % RGB values of the two layers, pixel by pixel)

This is all that's needed for the filter. There's nothing in there that you don't need.

A lot of times, SVG generators spit out a lot of unnecessary attributes, but this was handwritten and I only included what's really needed for it to work cross-browser.

2
  • We can use backdrop-filter to apply the filter to just the background
    – pavi2410
    Dec 11, 2023 at 3:55
  • 1
    @pavi2410 No, we can't because that's not what backdrop-filter does. backdrop-filter applies a filter to just the area underneath the semi-transparent (if it were opaque, we couldn't see the filter effect) background element it's set on.
    – Ana
    Dec 11, 2023 at 20:59
9

While this doesn't qualify as true noise, a pure CSS3 approach would be using multiple repeating-linear-background selectors, which are often used in pattern generators.

Here are a few examples:

With some right combination of backgrounds, angles, color stops, and transparency, a reasonable noise-like effect should be achievable :)

Hope that sets you in the right direction anyways...

8

Yes, there's currently no CSS-based approach for noise textures. If you're hell-bent on a programmatic (rather than image-based) approach, though, you could try using HTML5 canvas. There's a tutorial here on how to generate noise using JavaScript --> Creating Noise in HTML5 Canvas

However, doing the Canvas approach will result in a much slower experience for your visitors, because A) JavaScript is an interpreted language, and B) writing graphics using JS is extra slow.

So, unless you're trying to make a point by using HTML5, I'd stick with an image. It'll be faster (for you to make and for your users to load), and you'll have a finer degree of control over the appearance.

5
  • in certain cases (esp. on mobile where http-requests are even more expensive) it works even faster than actual loading! Jul 5, 2011 at 15:17
  • 1
    Or you could base-64 the image. HTTP requests aren't necessarily required.
    – derrylwc
    Oct 27, 2011 at 23:27
  • 1
    I had a measured use-case where an image with noise texture, 80x80, was weighing 10kb and after base64 it would add about 14kb of text to the css – that wasn't acceptable. In JS it's about 20 lines of code and it works fast enough (and faster than to load these 14kb of text over slow network). Oct 28, 2011 at 7:31
  • Definitely a good justification to use JS. Although 10kb seems a bit steep! 40x40 pixels should provide plenty entropy for a repeatable noise texture, and comes in under 2kb. It all comes down to your particular situation.
    – derrylwc
    Oct 31, 2011 at 22:01
  • You can use CSS to do this :/
    – tim.baker
    Oct 4, 2013 at 0:58
7

Building on top of Clint Pachl's answer, I used CSS's mix-blend-mode to get a grainier effect and to selectively punch up the colors of that make up the gradient.

See https://jsfiddle.net/jimmmy/2ytzh30w/ for example code.

Update: I wrote an article about it in CSS-Tricks: Grainy Gradients

Noise using css

0
2

It is not possible (even if it was, it'd take a crapton of code tricks to do so) to generate noise textures using CSS alone. There aren't any new CSS3 properties that provide that sort of effect out of the box. A much quicker solution is to use a graphic editor such as Photoshop to do that.

2
  • so would you suggest creating a texture in photoshop and repeating x and y?
    – austin
    Oct 25, 2010 at 0:14
  • 1
    @austin: Yeah. You can either create the noise as a repeating transparent PNG alone and place it as a background-image, or include the radial gradient in your image instead and make it non-repeat, although it's more compatible you have to keep it an exact size.
    – BoltClock
    Oct 25, 2010 at 0:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.