search
HomeWeb Front-endCSS TutorialAre There Random Numbers in CSS?

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Where should 'Subscribe to Podcast' link to?Where should 'Subscribe to Podcast' link to?Apr 16, 2025 pm 12:04 PM

For a while, iTunes was the big dog in podcasting, so if you linked "Subscribe to Podcast" to like:

Browser Engine DiversityBrowser Engine DiversityApr 16, 2025 pm 12:02 PM

We lost Opera when they went Chrome in 2013. Same deal with Edge when it also went Chrome earlier this year. Mike Taylor called these changes a "Decreasingly

UX Considerations for Web SharingUX Considerations for Web SharingApr 16, 2025 am 11:59 AM

From trashy clickbait sites to the most august of publications, share buttons have long been ubiquitous across the web. And yet it is arguable that these

Weekly Platform News: Apple Deploys Web Components, Progressive HTML Rendering, Self-Hosting Critical ResourcesWeekly Platform News: Apple Deploys Web Components, Progressive HTML Rendering, Self-Hosting Critical ResourcesApr 16, 2025 am 11:55 AM

In this week's roundup, Apple gets into web components, how Instagram is insta-loading scripts, and some food for thought for self-hosting critical resources.

Git Pathspecs and How to Use ThemGit Pathspecs and How to Use ThemApr 16, 2025 am 11:53 AM

When I was looking through the documentation of git commands, I noticed that many of them had an option for . I initially thought that this was just a

A Color Picker for Product ImagesA Color Picker for Product ImagesApr 16, 2025 am 11:49 AM

Sounds kind of like a hard problem doesn't it? We often don't have product shots in thousands of colors, such that we can flip out the with . Nor do we

A Dark Mode Toggle with React and ThemeProviderA Dark Mode Toggle with React and ThemeProviderApr 16, 2025 am 11:46 AM

I like when websites have a dark mode option. Dark mode makes web pages easier for me to read and helps my eyes feel more relaxed. Many websites, including

Some Hands-On with the HTML Dialog ElementSome Hands-On with the HTML Dialog ElementApr 16, 2025 am 11:33 AM

This is me looking at the HTML element for the first time. I've been aware of it for a while, but haven't taken it for a spin yet. It has some pretty cool and

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft