Generate random color with pure CSS (no javascript)?

后端 未结 6 1907
终归单人心
终归单人心 2021-02-06 23:57

Is it possible to generate random color with pure CSS and without using javascript? It\'s probably impossible but I\'m still curious.

6条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-07 00:06

    This isn't really possible in pure CSS.

    However, using a pre-processor like SASS (example) or LESS (example) can generate random colors for you because they are built using scripting languages.


    One side note that may help readers in the future is the possibility for using CSS variables. We can declare a CSS variable by saying

    element {
      --main-bg-color: brown;
    }
    

    and use it like so:

    element {
      background-color: var(--main-bg-color);
    }
    

    Now we can change it using JS:

    // From http://stackoverflow.com/a/5365036/2065702
    var randomColor = "#"+((1<<24)*Math.random()|0).toString(16); 
    
    document.documentElement.style.setProperty('main-bg-color', randomColor);
    

    Or you could use a completely different way of selecting a random color (like user input). This allows for possibilities like theming. One thing you have to consider is browser support because it's not great right now.

提交回复
热议问题