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>/* 活動標簽將是靜態(tài)的,并移出窗口*/ 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

Undress AI Tool
Undress images for free

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

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

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)

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

The choice of CSS units depends on design requirements and responsive requirements. 1.px is used for fixed size, suitable for precise control but lack of elasticity; 2.em is a relative unit, which is easily caused by the influence of the parent element, while rem is more stable based on the root element and is suitable for global scaling; 3.vw/vh is based on the viewport size, suitable for responsive design, but attention should be paid to the performance under extreme screens; 4. When choosing, it should be determined based on whether responsive adjustments, element hierarchy relationships and viewport dependence. Reasonable use can improve layout flexibility and maintenance.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.
