Table of Contents
Randomization from other languages
Why do I care about random values ​​in CSS?
Simulate random dice rolls
This technique has some obvious disadvantages
Home Web Front-end CSS Tutorial Are There Random Numbers in CSS?

Are There Random Numbers in CSS?

Apr 15, 2025 am 09:37 AM

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>
Copy after login

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>
Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1237
24
Google Fonts   Variable Fonts Google Fonts Variable Fonts Apr 09, 2025 am 10:42 AM

I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference

How to Create an Animated Countdown Timer With HTML, CSS and JavaScript How to Create an Animated Countdown Timer With HTML, CSS and JavaScript Apr 11, 2025 am 11:29 AM

Have you ever needed a countdown timer on a project? For something like that, it might be natural to reach for a plugin, but it’s actually a lot more

HTML Data Attributes Guide HTML Data Attributes Guide Apr 11, 2025 am 11:50 AM

Everything you ever wanted to know about data attributes in HTML, CSS, and JavaScript.

A Proof of Concept for Making Sass Faster A Proof of Concept for Making Sass Faster Apr 16, 2025 am 10:38 AM

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

How We Created a Static Site That Generates Tartan Patterns in SVG How We Created a Static Site That Generates Tartan Patterns in SVG Apr 09, 2025 am 11:29 AM

Tartan is a patterned cloth that’s typically associated with Scotland, particularly their fashionable kilts. On tartanify.com, we gathered over 5,000 tartan

How to Build Vue Components in a WordPress Theme How to Build Vue Components in a WordPress Theme Apr 11, 2025 am 11:03 AM

The inline-template directive allows us to build rich Vue components as a progressive enhancement over existing WordPress markup.

PHP is A-OK for Templating PHP is A-OK for Templating Apr 11, 2025 am 11:04 AM

PHP templating often gets a bad rap for facilitating subpar code — but that doesn&#039;t have to be the case. Let’s look at how PHP projects can enforce a basic

Programming Sass to Create Accessible Color Combinations Programming Sass to Create Accessible Color Combinations Apr 09, 2025 am 11:30 AM

We are always looking to make the web more accessible. Color contrast is just math, so Sass can help cover edge cases that designers might have missed.

See all articles