What is the best way to ensure the default style is applied when validating?

input {
  background: white;
  color: white;
}
input:in-range {
  background: green;
  color: white;
}
input:out-of-range {
  background: red;
  color: white;
}
<h3> CSS range validation </h3>
Enter your age
<input type="number" min="1" max="100">

Purpose:

  • white for out-of-range (default case)
  • green for in-range
  • red for out-of-range

In the code above, is there a way to modify

input {
   background: white;
   color: white;
}

so it applies only to input without considering in-range or out-of-range?

Answer №1

It appears that the pseudo-classes :in-range and :out-of-range behave similarly to the :valid and :invalid selectors. This results in the input element always being in one of these states, preventing the default selector from being applied. Interestingly, even a blank value is considered to be in range, despite seeming otherwise. The selectors specification does not address this specific scenario.

An advisable solution would be to set a default value for the field (e.g., value="0") since it is mandatory. However, if you find that the default red background negatively impacts the user experience, consider the following alternative approach.

By adding the required attribute to the input (given its mandatory nature) and combining it with the :valid and :invalid selectors, the desired outcome can be achieved.

  • input:invalid - Applied in cases of default or blank values as they are deemed invalid due to the field's required status.
  • input:in-range:valid - Selects any valid value within the specified range.
  • input:out-of-range:invalid - Identifies values outside the defined range as invalid, triggering the red color only when relevant.

Note for future readers: While the suggested workaround may suffice for some scenarios, it is worth noting that users may expect a blank value in a required field to also trigger an invalid state with a red background. It is advised to evaluate and apply cautiously.

input:invalid {
  background: white;
  color: white;
}
input:in-range:valid {
  background: green;
  color: white;
}
input:out-of-range:invalid {
  background: red;
  color: white;
}
<h3> CSS range validation </h3>
Enter your age
<input type="number" min="1" max="100" required>

Answer №2

Unfortunately, CSS is not capable of determining if a text box is empty based on specific conditions. However, there is an alternative solution that involves using JavaScript. For more information, you can refer to this discussion thread.


You can try adding a class to apply styles only when certain classes are present on the element.

CSS

input[type="number"] {
    background: white;
    color: black;
}
input[type="number"].validate:in-range {
    background: green;
    color: white;
}
input[type="number"].validate:out-of-range {
    background: red;
    color: white;
}

HTML

<h3> CSS range validation </h3>
Enter your age
<input class="validate" type="number" min="1" max="100">

<h3> NO CSS range validation </h3>
Enter your age
<input type="number" min="1" max="100">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize multiple background images in CSS with a set of three unique images

I have inserted three images into the background of my website's body. Two of them are displaying correctly (one with repeat-y), but the third one is not working. I've tried searching a lot but couldn't find a solution. body { backgr ...

Centering the logo using Material-UI's alignment feature

Need help centering a logo in my login form using Material-UI. Everything else is centered except for the logo, which is stuck to the left side of the card. I've tried adding align="center" and justify="center" under the img tag, but it's still ...

Transfer the contents from the text box field into the <p> tag

I know how to transfer text from one textbox to another in JS, but I'm interested in moving the text from a textbox to a paragraph. Can anyone explain how to achieve this? Thank you Update: Apologies for not being more specific earlier. I'm att ...

Checking the alignment of a label or element in the center of a webpage using javascript

I am new to JavaScript and was attempting to determine if an element is centered aligned by accessing its CSS properties/values. Can someone help me retrieve the CSS property to verify text alignment using JavaScript? ...

The HTML code displays the changes in output after resizing the screen

Currently, I am utilizing canvas(graph) within my Angular JS UI5 application. My main goal is to increase the width of the graph. However, whenever I attempt to adjust the size of the Graph, it remains unchanged. Interestingly, when I shrink the screen, th ...

How can you customize gutter widths for specific rows in Bootstrap 3?

Currently, I am constructing my own website using Bootstrap 3 and have come across a challenge that I would like to address: My goal is to assign distinctive gutter widths to certain rows in my design. The remaining sections of the site will adhere to th ...

Divide text to reduce its width within the confines of a specific height on a div element

I've spent the past week scouring various forums, including stackoverflow, but I haven't been able to find a solution. In my responsive website, I'm using CSS flexbox to display dynamic menu items. Sometimes the text can be quite long, and ...

Using a CSS selector to retrieve text following the aria-label attribute

I am attempting to retrieve the text "Verified account" from an element that looks like this: <svg viewBox="0 0 24 24" aria-label="Verified account" class="r-13gxpu9 r-4qtqp9 r-yyyyoo r-1xvli5t r-9cviqr r-dnmrzs r-bnwqim r-1plcr ...

Storing User Information in Cookies using jQuery

My current jQuery script is linked to a button and it functions by toggling font styles on a website by enabling or disabling a stylesheet upon clicking the button. Now, I want to enhance this functionality by saving user preference to a cookie so that the ...

What causes Safari to display a black border around resized videos?

I've come across a strange issue while using Safari. Whenever I try to play an MP4 video with dimensions of 1920 * 1080, and resize the Safari window to a width of 937px, something strange happens: https://i.stack.imgur.com/oI50i.png A black border ...

Is there a way to switch up the dropdown chevron using only CSS after a click?

Is there a way to change the appearance of dropdown arrows using only CSS and animations when clicked on? I attempted the following method: body { background: #000; } #sec_opt select { /* Reset */ -webkit-appearance: none; -moz-appearance: n ...

JavaScript event/Rails app encounters surprising outcome

I have encountered a strange bug in my JavaScript code. When I translate the page to another language by clicking on "English | Русский" using simple I18n translation, my menu buttons stop working until I reload the page. I suspect that the issue ...

Placing an absolutely positioned element on top of other elements

Currently, I am working on a frontendmentor website and encountering difficulty in positioning the shopping cart div above all the other elements. Initially, I attempted to use z-index for this purpose, but it seems that it does not work with elements havi ...

Unable to convert cursor to jpg format

I am facing an issue where I have a jpg file stored in the same folder as my styles.css, and I want to change the cursor on a webpage to this particular jpg file. Despite my efforts, it seems like the cursor is not changing as expected. Currently, I am us ...

Which takes precedence: the end of the script tag or the backtick?

Currently, I am working on developing a page builder widget. My goal is to save the entirety of the HTML code for the edited page to both local storage and a database. The PHP script will load the saved HTML from the database, while JavaScript will handle ...

"Want to extend the current date (Y-m-d) by a few days? Here

On my form, there is a date input that I want to automatically set to the date that is 14 days from today. I know how to set the value to today's date, but how can I add 14 days to it? <p>Term:<br> <input type="date" name="term" i ...

Turn off background sound on mobile devices

I have a question about the script I'm using to play a background audio theme on my website - is there a way to prevent it from automatically playing on mobile devices? $(document).ready(function() { var audioElement = document.createElement ...

The Art of Dynamic Component Manipulation in Angular

The current official documentation only demonstrates how to dynamically alter components within an <ng-template> tag. https://angular.io/guide/dynamic-component-loader My goal is to have 3 components: header, section, and footer with the following s ...

Troubles with CSS Child Hover, Rotation, and Clipping in Pie Chart styling

The issue I am facing is with a 3-section pie chart where all sections look virtually identical. However, the :hover effect does not trigger on the first section, but it works on the other two. Each element has an equal number of overlapping parent divs, ...

Standard tag for all JSP pages including doctype declaration and styles

I have multiple .jsp files and a page.tag that contains information about all the .jsp files. I don't want to include doctype, styles, and scripts in every single .jsp file, as it would require changing them individually if any updates are needed. Ins ...