Are There Random Numbers in CSS?
CSS gives web pages dynamic layout and interaction capabilities, but as a static language, once the value is set, it cannot be changed. Therefore, the concept of randomness does not apply here. Generating random numbers at runtime is the realm of JavaScript, not CSS. Or, not exactly? If we add a little user interaction, we can actually generate a certain degree of randomness in CSS. Let's take a look!
Randomization from other languages
As Robin Rendle explained in a CSS-Tricks article, CSS variables can be used to achieve some degree of "dynamic randomization". But these schemes are not entirely CSS-based, because they require JavaScript to update CSS variables to include new random values.
We can use preprocessors such as Sass or Less to generate random values, but once the CSS code is compiled and exported, these values are fixed and the randomness disappears. As Jake Albaugh explains:
Random in Sass is like randomly choosing the name of the protagonist in the story. It is only random when written, it won't change.
— jake albaugh (@jake_albaugh) December 29, 2016
Why do I care about random values in CSS?
In the past, I have developed simple pure CSS applications such as trivia games, Simon games and magic tricks. But I want to do something more complicated. I will leave it to you later on the discussion on the effectiveness, utility or feasibility of creating these pure CSS fragments.
Based on the premise that some board games can be represented by finite state machines (FSM), they can be represented by HTML and CSS. So I started developing a snake ladder game (also called Chutes and Ladders). This is a simple game. The goal is to push the piece from the starting point to the end of the board by avoiding the snake and trying to climb up the ladder.
This project seems to work, but I am missing one thing: roll the dice !
Dice rolls (and coin toss) are generally considered randomized. You roll dice or coin and you get an unknown value each time.
Simulate random dice rolls
I'm going to overlay the layer with the label and use CSS animation to "rotate" and swap which layer is on top. Like this:
The code to simulate this randomness is not complicated and can be implemented using animations and different animation delays:
<code>/* 最高的z-index是骰子的面数*/ @keyframes changeOrder { from { z-index: 6; } to { z-index: 1; } } /* 所有标签都使用绝对定位重叠*/ label { animation: changeOrder 3s infinite linear; background: #ddd; cursor: pointer; display: block; left: 1rem; padding: 1rem; position: absolute; top: 1rem; user-select: none; } /* 负延迟,以便动画的所有部分都在运动*/ label:nth-of-type(1) { animation-delay: -0.0s; } label:nth-of-type(2) { animation-delay: -0.5s; } label:nth-of-type(3) { animation-delay: -1.0s; } label:nth-of-type(4) { animation-delay: -1.5s; } label:nth-of-type(5) { animation-delay: -2.0s; } label:nth-of-type(6) { animation-delay: -2.5s; }</code>
The animation has slowed down to facilitate interaction (but still fast enough to see the obstacles explained below). The pseudo-randomness is also clearer.
But then I ran into a barrier: I got the random number, but sometimes even if I click on my "dice", it doesn't return any value.
I tried increasing the animation time and this seemed to help, but I still encountered some unexpected values.
At this point, I do what most developers do when they encounter obstacles that cannot be solved by searching online only: I ask other developers for help in the form of StackOverflow issues.
Fortunately, Temani Afif, who always has resources, comes up with an explanation and a solution.
Simply put, the problem is that the browser will only trigger the click/press event when the element activated when the mouse is pressed is the same as the element activated when the mouse is lifted.
Due to the rotation animation, the top label when the mouse is pressed is not the top label when the mouse is lifted, unless I let the animation loop fast or slow enough. This is why increasing animation time hides these problems.
The solution is to apply the "static" position to break the stacking context and use pseudo-elements with higher z-index (like ::before or ::after) to occupy its position. This way, the active tag will always be on top when the mouse is raised.
<code>/* 活动标签将是静态的,并移出窗口*/ label:active { margin-left: 200%; position: static; } /* 标签的伪元素占据所有空间,并具有更高的z-index */ label:active::before { content: ""; position: absolute; top: 0; right: 0; left: 0; bottom: 0; z-index: 10; }</code>
Here is the code containing the solution, the animation time is faster:
After making this change, the only thing left is to create a small interface to draw a fake dice to click on, and the pure CSS snake ladder game is done.
This technique has some obvious disadvantages
- Requires user input: the tag must be clicked to trigger "random number generation".
- Not very scalable: It works with small value sets, but is troublesome for large ranges.
- It's not really random, but pseudo-random: the computer can easily detect which value will be generated at each moment.
But on the other hand, it is 100% CSS (no preprocessor or other external helper required), and for human users it can look 100% random.
Speaking of hand... this method can be used not only for random numbers, but also for anything random. In this case, we use it to "randomly" choose the computer choice in the stone scissors game:
The above is the detailed content of Are There Random Numbers in CSS?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

It's out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That's like this.

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

I'd say "website" fits better than "mobile app" but I like this framing from Max Lynch:

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...
