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!

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements.

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more.


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

Dreamweaver CS6
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

Zend Studio 13.0.1
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
