Стили HTML форм
В этой статье Вы узнает, как использовать CSS с HTML-формами, чтобы сделать их (надеюсь) более красивыми. Удивительно, но это может быть немного сложнее. По историческим и техническим причинам виджеты форм плохо сочетаются с CSS. Из-за этих трудностей многие разработчики предпочитают создавать свои собственные HTML-виджеты, чтобы получить контроль над своим внешним видом. Однако в современных браузерах веб-дизайнеры все больше контролируют дизайн элементов формы. Давайте приступим!
Почему так сложно стилизовать виджеты форм с помощью CSS?
На заре Интернета, примерно в 1995 году, в HTML 2 были добавлены элементы управления формой. Из-за сложности виджетов форм разработчики решили полагаться на базовую операционную систему для управления ими и их рендеринга.
Несколько лет спустя был создан CSS, и то, что было технической необходимостью, то есть использование собственных виджетов для реализации элементов управления формой, стало требованием к стилю. В первые дни CSS, стилизация элементов управления формы не была приоритетом.
Поскольку пользователи привыкли к внешнему виду своих соответствующих платформ, поставщики браузеров неохотно делают элементы управления формами стилевыми; и по сей день все ещё чрезвычайно трудно перестроить все элементы управления, чтобы сделать их стилизованными.
Даже сегодня ни один браузер полностью не реализует CSS 2.1. Однако со временем поставщики браузеров улучшили свою поддержку CSS для элементов формы, и, несмотря на плохую репутацию в отношении удобства использования, теперь вы можете использовать CSS для стилизации HTML форм (en-US) .
Не все виджеты созданы равными, когда задействован CSS
В настоящее время некоторые трудности остаются при использовании CSS с формами. Эти проблемы можно разделить на три категории:
Хорошая
Некоторые элементы могут быть стилизованы с небольшим количеством проблем на разных платформах. К ним относятся следующие структурные элементы:
Сюда также входят все виджеты текстового поля (как однострочные, так и многострочные) и кнопки.
Плохая
Некоторые элементы редко могут быть стилизованы, и могут потребовать некоторых сложных уловок, иногда требующих углублённых знаний CSS3.
Они включают в себя элемент , но его нельзя правильно расположить на всех платформах. Флажки и переключатели также не могут быть стилизованы напрямую, однако, благодаря CSS3 вы можете обойти это. Контент placeholder не может быть стилизован каким-либо стандартным способом, однако все браузеры, которые его реализуют, также реализуют собственные псевдо-элементы CSS или псевдоклассы, которые позволяют его стилизовать.
Мы опишем, как обрабатывать эти более конкретные случаи, в статье «Расширенные стили для HTML-форм». (en-US)
The ugly
Some elements simply can’t be styled using CSS. These include: all advanced user interface widgets, such as range, color, or date controls; and all the dropdown widgets, including , , and elements. The file picker widget is also known not to be stylable at all. The new and elements also fall in this category.
The main issue with all these widgets, comes from the fact that they have a very complex structure, and CSS is not currently expressive enough to style all the subtle parts of those widgets. If you want to customize those widgets, you have to rely on JavaScript to build a DOM tree you’ll be able to style. We explore how to do this in the article How to build custom form widgets (en-US) .
Basic styling
To style elements that are easy to style (en-US) with CSS, you shouldn’t face any difficulties, since they mostly behave like any other HTML element. However, the user-agent style sheet of every browser can be a little inconsistent, so there are a few tricks that can help you style them in an easier way.
Search fields
Search boxes are the only kind of text fields that can be a little tricky to style. On WebKit based browsers (Chrome, Safari, etc.), you’ll have to tweak it with the -webkit-appearance proprietary property. We discuss this property further in the article: Advanced styling for HTML forms (en-US) .
Example
form> input type="search" /> form>
input[type="search"] border: 1px dotted #999; border-radius: 0; -webkit-appearance: none; >

As you can see on this screenshot of the search field on Chrome, the two fields have a border set as in our example. The first field is rendered without using the -webkit-appearance property, whereas the second is rendered using -webkit-appearance:none . This difference is noticeable.
Fonts and text
CSS font and text features can be used easily with any widget (and yes, you can use @font-face with form widgets). However, browsers’ behaviors are often inconsistent. By default, some widgets do not inherit font-family and font-size from their parents. Many browsers use the system default appearance instead. To make your forms’ appearance consistent with the rest of your content, you can add the following rules to your stylesheet:
button, input, select, textarea font-family: inherit; font-size: 100%; >
The screenshot below shows the difference; on the left is the default rendering of the element in Firefox on Mac OS X, with the platform’s default font style in use. On the right are the same elements, with our font harmonization style rules applied.

There’s a lot of debate as to whether forms look better using the system default styles, or customized styles designed to match your content. This decision is yours to make, as the designer of your site, or Web application.
Box model
All text fields have complete support for every property related to the CSS box model ( width , height , padding , margin , and border ). As before, however, browsers rely on the system default styles when displaying these widgets. It’s up to you to define how you wish to blend them into your content. If you want to keep the native look and feel of the widgets, you’ll face a little difficulty if you want to give them a consistent size.
This is because each widget has their own rules for border, padding and margin. So if you want to give the same size to several different widgets, you have to use the box-sizing property:
input, textarea, select, button width: 150px; margin: 0; -webkit-box-sizing: border-box; /* For legacy WebKit based browsers */ -moz-box-sizing: border-box; /* For legacy (Firefox <29) Gecko based browsers */box-sizing: border-box; >

In the screenshot above, the left column is built without box-sizing , while the right column uses this property with the value border-box . Notice how this lets us ensure that all of the elements occupy the same amount of space, despite the platform’s default rules for each kind of widget.
Positioning
Positioning of HTML form widgets is generally not a problem; however, there are two elements you should take special note of:
Как изменить input css
Элемент HTML используется для создания интерактивных элементов управления в веб-формах для получения данных от пользователя; в зависимости от устройства и user agent, доступен широкий выбор типов входных данных и виджетов управления. Из-за огромного количества возможных сочетаний типов ввода и атрибутов это один из самых мощных и сложных элементов HTML.
- Content categories (en-US)Flow content (en-US), listed, submittable, resettable, form-associated element, phrasing content (en-US). If the type has not the hidden value, labellable element, palpable content.
- Permitted content None, it is an empty element.
- Tag omission Must have a start tag and must not have an end tag.
- Permitted parent elements Any element that accepts phrasing content (en-US).
- DOM interfaceHTMLInputElement (en-US)
Атрибуты
- Расширение файла, начинающееся с символа точки (U+002E). Наприм., ‘.jpg, .png, .doc)
- Валидный тип MIME без расширения
- audio/* для аудиофайлов
- video/* для видеофайлов
- image/* для файлов с изображениями
Тип элемента для отображения. Если этот атрибут не указан, по умолчанию используется text . Возможными значениями являются:
- button : Кнопка без предопределённого поведения.
- checkbox : Флажок («чекбокс»). Следует использовать атрибут value для определения значения, которое будет отдано этим элементом. Используйте атрибут checked, чтобы указать, должен ли флажок быть выставлен. Можно также использовать атрибут indeterminate, чтобы указать, что флажок находится в неопределённом состоянии (на большинстве платформ при этом рисуется горизонтальная линия поперёк флажка).
- color : Элемент управления цветом. Пользовательский интерфейс выбора цвета не имеет никаких других функций, кроме принятия простых цветов в виде текста (больше информации).
- date : Элемент управления для ввода даты (год, месяц и день, без времени).
- datetime : Элемент управления для ввода даты и времени (час, минута, секунда и доля секунды) в соответствии с часовым поясом UTC.
- datetime-local : Элемент управления для ввода даты и времени без часового пояса.
- email : Поле для редактирования адреса электронной почты. Перед отправкой проверяется, что входное значение содержит либо пустую строку, либо один действительный адрес электронной почты. Соответствуют CSS псевдоклассам :valid and :invalid .
- file : Элемент управления, который позволяет пользователю выбрать файл. Используйте атрибут accept, чтобы определить типы файлов, которые могут быть выбраны.
- hidden : Элемент управления, которые не отображается, но чьё значение отправлено на сервер.
- image : Кнопка вставки изображения. Вы должны использовать атрибут src, чтобы определить путь к изображению и атрибут alt — для определения альтернативного текста. Вы можете использовать атрибуты height и width, чтобы определить размер вставки изображения в пикселях.
- month : Элемент управления для ввода месяца и года без часового пояса.
- number : Элемент управления ввода числа(тип float).
- password : Однострочное текстовое поле, чьё значение скрыто символом «звёздочка». Используйте атрибуты minlength и maxlength, чтобы указать минимальную и максимальную длину значения, которое может быть введено.
Примечание: Любые формы, в которых присутствует важная информация(например, пароль), должны быть обработаны через HTTPS; в настоящий момент Firefox реализует составной механизм предупреждения, направленные против небезопасных форм для входа в систему — смотрите Небезопасные пароли (en-US) .
- min : 0
- max : 100
- value : min + ( max — min )/2, or min if max is less than min
- step : 1
В случае, если значением атрибута type является file , данный атрибут определяет типы файлов, которые сервер может принять. В противном случае файл игнорируется. Значение должно быть списком уникальных спецификаторов типов содержания, разделённым запятыми:
Одиночный символ, который пользователь может нажать, чтобы переключить фокус на элемент управления.
Определяет «действие-подсказку», которая используется для определения того, как будет обозначаться клавиша enter на мобильных устройствах с виртуальной клавиатурой. Поддерживаемые значения: go , done , next , search , и send ; они автоматически сопоставляются с необходимой строкой (являются чувствительными к регистру).
Этот атрибут указывает, разрешено ли автоматическое заполнение поля браузером. Разрешено по умолчанию, даже если не указано. Данный атрибут игнорируется, если атрибут type равен hidden, password, checkbox , radio , file , или type кнопка ( button , submit , reset , image ). Возможные значения:
- off : Пользователь должен каждый раз полностью вводить значение в поле или документ предусматривает свой собственный метод автозаполнения; браузер не делает автоматического заполнения записи.
- on : Браузер автоматически заканчивает значение поля, основываясь на значениях, которые вводились пользователем ранее.Если не атрибут autocomplete не указан в , тогда браузер использует атрибут autocomplete формы, которая является родительской для данной формы. The form owner is either the form element that this element is a descendant of or the form element whose id is specified by the form attribute of the input element. For more information, see the autocomplete attribute in .
This Boolean attribute lets you specify that a form control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form element in a document can have the autofocus attribute, which is a Boolean. It cannot be applied if the type attribute is set to hidden (that is, you cannot automatically set focus to a hidden control).
This attribute should be defined as a unique value. If the value of the type attribute is search , previous search term values will persist in the dropdown across page load.
When the value of the type attribute is radio or checkbox , the presence of this Boolean attribute indicates that the control is selected by default; otherwise it is ignored.
This Boolean attribute indicates that the form control is not available for interaction. In particular, the click event will not be dispatched on disabled controls. Also, a disabled control’s value isn’t submitted with the form.
The URI of a program that processes the information submitted by the input element, if it is a submit button or image. If specified, it overrides the action attribute of the element’s form owner.
If the input element is a submit button or image, this attribute specifies the type of content that is used to submit the form to the server. Possible values are:
- application/x-www-form-urlencoded : The default value if the attribute is not specified.
- multipart/form-data : Use this value if you are using an element with the type attribute set to file .
- text/plain If this attribute is specified, it overrides the enctype attribute of the element’s form owner.
If the input element is a submit button or image, this attribute specifies the HTTP method that the browser uses to submit the form. Possible values are:
- post : The data from the form is included in the body of the form and is sent to the server.
- get : The data from the form are appended to the form attribute URI, with a ‘?’ as a separator, and the resulting URI is sent to the server. Use this method when the form has no side-effects and contains only ASCII characters.If specified, this attribute overrides the method attribute of the element’s form owner.
If the input element is a submit button or image, this Boolean attribute specifies that the form is not to be validated when it is submitted. If this attribute is specified, it overrides the novalidate attribute of the element’s form owner.
If the input element is a submit button or image, this attribute is a name or keyword indicating where to display the response that is received after submitting the form. This is a name of, or keyword for, a browsing context (for example, tab, window, or inline frame). If this attribute is specified, it overrides the target attribute of the elements’s form owner. The following keywords have special meanings:
- _self : Load the response into the same browsing context as the current one. This value is the default if the attribute is not specified.
- _blank : Load the response into a new unnamed browsing context.
- _parent : Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as _self .
- _top : Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as _self .
If the value of the type attribute is image , this attribute defines the height of the image displayed for the button.
A hint to the browser for which keyboard to display. This attribute applies when the value of the type attribute is text, password, email, or url. Possible values are:
- verbatim : Alphanumeric, non-prose content such as usernames and passwords.
- latin : Latin-script input in the user’s preferred language with typing aids such as text prediction enabled. For human-to-computer communication such as search boxes.
- latin-name : As latin, but for human names.
- latin-prose : As latin, but with more aggressive typing aids. For human-to-human communication such as instant messaging for email.
- full-width-latin : As latin-prose, but for the user’s secondary languages.
- kana : Kana or romaji input, typically hiragana input, using full-width characters, with support for converting to kanji. Intended for Japanese text input.
- katakana : Katakana input, using full-width characters, with support for converting to kanji. Intended for Japanese text input.
- numeric : Numeric input, including keys for the digits 0 to 9, the user’s preferred thousands separator character, and the character for indicating negative numbers. Intended for numeric codes, e.g. credit card numbers. For actual numbers, prefer using
- tel : Telephone input, including asterisk and pound key. Use if possible instead.
- email : Email input. Use if possible instead.
- url : URL input. Use if possible instead.
The maximum (numeric or date-time) value for this item, which must not be less than its minimum (min attribute) value.
If the value of the type attribute is text , email , search , password , tel , or url , this attribute specifies the maximum number of characters (in Unicode code points) that the user can enter; for other control types, it is ignored. It can exceed the value of the size attribute. If it is not specified, the user can enter an unlimited number of characters. Specifying a negative number results in the default behavior; that is, the user can enter an unlimited number of characters. The constraint is evaluated only when the value of the attribute has been changed.
The minimum (numeric or date-time) value for this item, which must not be greater than its maximum (max attribute) value.
If the value of the type attribute is text , email , search , password , tel , or url , this attribute specifies the minimum number of characters (in Unicode code points) that the user can enter; for other control types, it is ignored.
Этот Boolean атрибут указывает, может ли пользователь вводить несколько значений. Этот атрибут применяется, если для атрибута type задано значение email или file ; в противном случае он игнорируется.
The name of the control, which is submitted with the form data.
A regular expression that the control’s value is checked against. The pattern must match the entire value, not just some subset. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is text , search , tel , url or email ; otherwise it is ignored. The regular expression language is the same as JavaScript’s. The pattern is not surrounded by forward slashes.
A hint to the user of what can be entered in the control . The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the type attribute is text , search , tel , url or email ; otherwise it is ignored.
This Boolean attribute indicates that the user cannot modify the value of the control. This attribute is ignored if the value of the type attribute is hidden , range , color , checkbox , radio , file , or a button type.
This attribute specifies that the user must fill in a value before submitting a form. It cannot be used when the type attribute is hidden , image , or a button type ( submit , reset , or button ). The :optional and :required CSS pseudo-classes will be applied to the field as appropriate.
The direction in which selection occurred. This is «forward» if the selection was made from left-to-right in an LTR locale or right-to-left in an RTL locale, or «backward» if the selection was made in the opposite direction. This can be «none» if the selection direction is unknown.
The initial size of the control. This value is in pixels unless the value of the type attribute is text or password , in which case, it is an integer number of characters. Starting in HTML5, this attribute applies only when the type attribute is set to text , search , tel , url , email , or password ; otherwise it is ignored. In addition, the size must be greater than zero. If you don’t specify a size, a default value of 20 is used.
Setting the value of this attribute to true indicates that the element needs to have its spelling and grammar checked. The value default indicates that the element is to act according to a default behavior, possibly based on the parent element’s own spellcheck value. The value false indicates that the element should not be checked.
If the value of the type attribute is image , this attribute specifies a URI for the location of an image to display on the graphical submit button; otherwise it is ignored.
Works with the min and max attributes to limit the increments at which a numeric or date-time value can be set. It can be the string any or a positive floating point number. If this attribute is not set to any , the control accepts only values at multiples of the step value greater than the minimum.
The position of the element in the tabbing navigation order for the current document.
The initial value of the control. This attribute is optional except when the value of the type attribute is radio or checkbox . Note that when reloading the page, Gecko and IE will ignore the value specified in the HTML source, if the value was changed before the reload.
If the value of the type attribute is image , this attribute defines the width of the image displayed for the button.
This Mozilla extension allows you to specify the error message to display when a field doesn’t successfully validate.
Notes
File inputs
Примечание: Starting in Gecko 2.0, calling the click() method on an element of type «file» opens the file picker and lets the user select files. See Using files from web applications for an example and more details.
You can’t set the value of a file picker from a script; doing something like the following has no effect:
var e = getElementById("someFileInputElement"); e.value = "foo";
Error messages
If you want Firefox to present a custom error message when a field fails to validate, you can use the x-moz-errormessage attribute to do so:
input type="email" x-moz-errormessage="Please specify a valid email address." />
Note, however, that this is not standard and will not have an effect on other browsers.
Examples
A simple input box
input type="text" name="input" value="Type here" />
A common use-case scenario
form action="getform.php" method="get"> First name: input type="text" name="first_name" />br /> Last name: input type="text" name="last_name" />br /> E-mail: input type="email" name="user_email" />br /> input type="submit" value="Submit" /> form>
Using mozactionhint on Firefox mobile
You can use the mozactionhint attribute to specify the text for the label of the enter key on the virtual keyboard when your form is rendered on Firefox mobile. For example, to have a «Next» label, you can do this:
input type="text" mozactionhint="next" name="sometext" />

Specifications
| Specification |
|---|
| HTML Standard # the-input-element |
Совместимость с браузерами
BCD tables only load in the browser
[1] Распознаётся, но UI отсутствует.
[2] Отсутствует для type=»checkbox» и type=»radio» .
[3] В Safari autocapitalize=»words» переводит в верхний регистр каждый второй символ слова.
[4] datetime был удалён из спецификации и браузеров в пользу datetime-local .
Gecko notes
Starting in Gecko 9.0, Firefox for Android lets users capture images using their camera and upload them, without having to leave the browser. Web developers can implement this feature by simply specifying setting the accept attribute’s value to «image/*» on their file input, like this:
Firefox for Android sets a default background-image gradient on all type=»text» , type=»file» , type=»button» , and type=»submit» inputs. This can be disabled using background-image: none .
Firefox for Android also sets a default border on all elements.
See also
- Other form-related elements: , , , , , , , , (en-US), , , , and .
- Cross-browser HTML5 placeholder text
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on 19 нояб. 2023 г. by MDN contributors.
Your blueprint for a better internet.
Is it possible to use an input value attribute as a CSS selector?
As npup explains in his answer, a simple css rule will only target the attribute value which means that this doesn’t cover the actual value of the html node.
JAVASCRIPT TO THE RESCUE!
- Ugly workaround: http://jsfiddle.net/QmvHL/
Original Answer
Yes it’s very possible, using css attribute selectors you can reference input’s by their value in this sort of fashion:
input[value="United States"] < color: #F90; >
• jsFiddle example
- [att] Match when the element sets the «att» attribute, whatever the value of the attribute.
- [att=val] Match when the element’s «att» attribute value is exactly «val».
- [att~=val] Represents an element with the att attribute whose value is a white space-separated list of words, one of which is exactly «val». If «val» contains white space, it will never represent anything (since the words are separated by spaces). If «val» is the empty string, it will never represent anything either.
- [att|=val] Represents an element with the att attribute, its value either being exactly «val» or beginning with «val» immediately followed by «-» (U+002D). This is primarily intended to allow language subcode matches (e.g., the hreflang attribute on the a element in HTML) as described in BCP 47 ([BCP47]) or its successor. For lang (or xml:lang) language subcode matching, please see the :lang pseudo-class.
1 1 1 silver badge
answered May 18, 2012 at 1:23
Michael Zaporozhets Michael Zaporozhets
23.8k 3 3 gold badges 31 31 silver badges 47 47 bronze badges
Does this only work for text? I can’t get this to work with type=»number».
May 30, 2013 at 19:06
@Mikey It seems as though the problem is that the styles don’t update when you update the value. Here’s an example of how it doesn’t work as I would expect: jsfiddle.net/VUXLT/4
Jun 6, 2013 at 23:13
@Luke I’ve updated my answer with a solution to that with javascript.
Jun 7, 2013 at 0:27
wouldn’t el.on(«change keydown keypress keyup», run); be better than setting a timeout?
Jun 7, 2013 at 10:55
@SamHasler probably but i’m not sure how foolproof change is considering the amount of different ways that the value can be modified
Jun 7, 2013 at 21:07
It is possible, if you’re using a browser which supports the CSS :valid pseudo-class and the pattern validation attribute on inputs — which includes most modern browsers except IE9.
For instance, to change the text of an input from black to green when the correct answer is entered:
input < color: black; >input:valid
Which country has fifty states?
answered Apr 13, 2015 at 18:43
Blazemonger Blazemonger
91.3k 26 26 gold badges 143 143 silver badges 181 181 bronze badges
This works much better than input[value] based solutions, because it validates the pattern as you type and therefore applies the style on the fly.
Aug 17, 2019 at 10:46
Is there a way to add more patterns?
Feb 3, 2022 at 7:10
Yes, but note: since the attribute selector (of course) targets the element’s attribute, not the DOM node’s value property (elem.value), it will not update while the form field is being updated.
Otherwise (with some trickery) I think it could have been used to make a CSS-only substitute for the «placeholder» attribute/functionality. Maybe that’s what the OP was after? 🙂
19.1k 16 16 gold badges 100 100 silver badges 115 115 bronze badges
answered Oct 26, 2012 at 7:32
2,531 1 1 gold badge 17 17 silver badges 22 22 bronze badges
It was what I was after. It makes sense though. Browsers only evaluate css rules when elements are rendered and changing the value wouldn’t cause the input to rerender.
Feb 11, 2013 at 22:04
@SamHasler Here’s an example of the value changing on load and the style being picked up: jsfiddle.net/bJMHC I believe the issue is entirely with the first point npop made.
Jun 6, 2013 at 23:52
@Mikey, it doesn’t update if you change the input directly though. The solution appears to be to update the attribute whenever the value of the input changes: jsfiddle.net/8u4AC
Jun 7, 2013 at 8:06
@SamHasler see my updated answer with a global workaround up the top 🙂
Jun 7, 2013 at 8:29
As mentioned before, you need more than a css selector because it doesn’t access the stored value of the node, so javascript is definitely needed. Heres another possible solution:
input:not([value=""])
answered Jan 9, 2014 at 22:09
161 1 1 silver badge 2 2 bronze badges
Using oninput instead of onkeyup may be beneficial, especially if you suspect that some users may use copy/paste.
Nov 9, 2017 at 23:05
input[value="United States"]
answered May 18, 2012 at 1:24
205k 31 31 gold badges 260 260 silver badges 272 272 bronze badges
Interestingly, if you change the HTML to initialize the input field with a different value (e.g. «China») and then manually (in the HTML form) change it to «United States», the CSS rule never gets invoked.
Aug 25, 2015 at 4:20
This is what I wanted to hear! It worked! In my case, my button value won’t change, so this is all I needed. Thanks.
Jun 22, 2016 at 16:52
I was wondering if it was possible to sniff user’s input if malicious CSS can be injected to a site. For example input[value|=»a»]
Feb 1, 2018 at 0:25
@علیرضا I think that keylogger doesn’t work because like kmoser said, the rules only match initial hard-coded value in html, but not the content entered by the end user.
Feb 23, 2018 at 20:39
You can use Css3 attribute selector or attribute value selector.
/This will make all input whose value is defined to red/
input[value]
/This will make conditional selection depending on input value/
input[value="United States"]
There are other attribute selector like attribute contains value selector,
input[value="United S"]
This will still make any input with United state as red text.
Than we attribute value starts with selector
input[value^='united']
Any input text starts with ‘united’ will have font color red
And the last one is attribute value ends with selector
input[value$='States']
Any input value ends with ‘States’ will have font color red
45.6k 23 23 gold badges 245 245 silver badges 245 245 bronze badges
answered Mar 5, 2015 at 12:14
13.5k 15 15 gold badges 76 76 silver badges 105 105 bronze badges
This is kind of correct, but might not work the way people are expecting. This only matches the value in the html «value» attribute, it does not work if you’re trying to match the current value of an input field which has been changed.
Mar 4 at 20:25
Refreshing attribute on events is a better approach than scanning value every tenth of a second.
inputElement.onchange = function() < this.setAttribute('value', this.value); >; inputElement.onkeyup = function() < this.setAttribute('value', this.value); >;
answered Nov 20, 2014 at 11:24
39 1 1 bronze badge
I strongly agree. This is much cleaner, more efficient, and doesn’t require jQuery for such basic functionality. This answer should probably still include example CSS to go along with it to be a complete answer, but if you need to apply different styles for various different specific values (as opposed to a single valid and invalid style), this is the way to go.
Feb 20 at 7:50
In Chrome 72 (2019-02-09) I’ve discovered that the :in-range attribute is applied to empty date inputs, for some reason!
So this works for me: (I added the :not([max]):not([min]) selectors to avoid breaking date inputs that do have a range applied to them:
input[type=date]:not([max]):not([min]):in-range

Here’s a runnable sample:
window.addEventListener( 'DOMContentLoaded', onLoad ); function onLoad()
label < display: block; margin: 1em; >input[type=date]:not([max]):not([min]):in-range
answered Feb 9, 2019 at 9:48
143k 28 28 gold badges 263 263 silver badges 379 379 bronze badges
Following the currently top voted answer, I’ve found using a dataset / data attribute works well.
//Javascript const input1 = document.querySelector("#input1"); input1.value = "0.00"; input1.dataset.value = input1.value; //dataset.value will set "data-value" on the input1 HTML element //and will be used by CSS targetting the dataset attribute document.querySelectorAll("input").forEach((input) => < input.addEventListener("input", function() < this.dataset.value = this.value; console.log(this); >) >)
/*CSS*/ input[data-value="0.00"]
Input1 is programmatically set by JavaScript:
Try typing 0.00 inside input2:
Pure CSS Inputs
Inputs are important in any webpage form. It is used to take various inputs from the user which are essential in collecting data or information.
Following are the various types of inputs in Pure CSS:
- Required Inputs
- Disabled Inputs
- Read Only Inputs
- Rounded Inputs
- Checkboxes and Radios
Required Inputs: If you want to mark a form control as required add the “required” attribute to the element. Suppose your form needs a phone number then you can use this attribute to show that a phone number is required.
Syntax:
Example:
HTML
< link rel = "stylesheet"
"sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w"
crossorigin = "anonymous" >
< h1 >Pure CSS Required Inputs h1 >
< input type = "tel"
placeholder = "Requires a phone number"
Output:
Disabled Inputs: If you don’t want to take any input from the user you can use disabled inputs. Add the “disabled” attribute to the element to disable form control.
Syntax:
Example:
HTML
< link rel = "stylesheet" href =
"sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w"
crossorigin = "anonymous" >
< h1 >Pure CSS Disabled Inputs h1 >
< input type = "text"
placeholder = "This input is disabled.."
Output:
Read-only Inputs: If you want to make a form input only readable, then you can use read only inputs. The major difference between read-only and disabled inputs is disabled inputs are not interactive whereas in read-only inputs you can interact with the input and select its text. Hence they are still focusable. Add “readonly” attribute to element to create read-only inputs.
Syntax:
Example: