Generate random color with pure CSS (no javascript)?

后端 未结 6 1906
终归单人心
终归单人心 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.

    0 讨论(0)
  • 2021-02-07 00:06
    <body style='background-color:<?php printf( "#%06X\n", mt_rand( 0, 0x222222 )); ?>'>
    

    Using PHP

    0 讨论(0)
  • 2021-02-07 00:09

    according to this site, http://blog.codepen.io/2013/08/26/random-function-in-sass/ its possible but not with pure css

    0 讨论(0)
  • 2021-02-07 00:10

    I found for you something here, but it uses PHP. I think it's impossible with plain CSS.

    0 讨论(0)
  • 2021-02-07 00:12

    Not really. Dynamism can only be implemented with the support of scripting.

    0 讨论(0)
  • 2021-02-07 00:16

    Not exactly random but with CSS:

    Step 1 - Select queried backgrounds, order them in sequence and adjust the frequency

        @keyframes bgrandom {
        0% { background: linear-gradient(90deg, rgba(255,255,255,0.98) 50%, rgba(255,255,255,0.96) 0%); }
        50% { background: linear-gradient(90deg, rgba(255,255,255,0.98) 50%, rgba(255,255,255,0.96) 0%); }
    
        55% { background: linear-gradient(90deg,  rgba(255,255,255,0.96) 50%, rgba(255,255,255,0.98) 0%); }
        80% { background: linear-gradient(90deg, rgba(255,255,255,0.96)  50%, rgba(255,255,255,0.98) 0%); }
    
        85% { background: linear-gradient(90deg, rgba(255,255,255,0.96) 50%, rgba(255,255,255,0.94) 0%); }
        100% { background: linear-gradient(90deg, rgba(255,255,255,0.96) 50%, rgba(255,255,255,0.94) 0%); }
        }
    

    Step 2 - Launch the animation(length animationName repeatMode)

        #element{  animation: 1.2s bgrandom infinite; }
    

    Easy to use, customize and works great. Similar technique can be used for sliders, spinners, etc.

    0 讨论(0)
提交回复
热议问题