What is Step Attribute in HTML: Explanation and Examples
step attribute in HTML defines the intervals or increments that a numeric or date input can accept. It controls how much the value changes when using input controls like sliders or number fields, ensuring users enter valid steps.How It Works
The step attribute works like a ruler for input fields that accept numbers or dates. Imagine you have a measuring tape marked in centimeters, and you only want to measure in 2 cm steps. The step attribute tells the browser to only allow values that fit those steps.
For example, if you set step="5" on a number input, the user can only select values like 0, 5, 10, 15, and so on. This helps prevent invalid or unexpected values and makes input easier to control.
It works with input types like number, range, date, time, and others that accept numeric or time values. The browser uses the step value to validate input and to adjust the value when using arrow keys or sliders.
Example
This example shows a number input where users can only select values in steps of 10, starting from 0.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Step Attribute Example</title> </head> <body> <label for="quantity">Quantity (step 10): </label> <input type="number" id="quantity" name="quantity" min="0" max="100" step="10" value="0"> </body> </html>
When to Use
Use the step attribute when you want to control the increments of numeric or date/time inputs. It is helpful when only certain values make sense, like:
- Choosing quantities in fixed amounts (e.g., packs of 5 items)
- Selecting time in 15-minute intervals
- Setting price ranges with specific increments
- Picking dates with a certain gap (e.g., every 7 days)
This improves user experience by preventing invalid inputs and making it easier to select valid values using keyboard or mouse controls.
Key Points
- The
stepattribute defines allowed increments for numeric or date/time inputs. - It works with input types like
number,range,date, andtime. - Setting
stephelps validate input and improves user control with arrows or sliders. - Use it to restrict input to meaningful intervals, improving form accuracy.