Disabled input with css

:disabled , :enabled

Эта кнопка серая. Она не доступна для клика. Как написать селектор на основе состояния элемента?

Время чтения: меньше 5 мин

Кратко

Скопировать ссылку «Кратко» Скопировано

Псевдоклассы :disabled и :enabled помогают стилизовать интерактивные элементы — на которые можно и нельзя нажать.

Легко применяются к любым элементам, которым можно задать атрибут disabled : , , , , , , , и .

Пример

Скопировать ссылку «Пример» Скопировано

Часто требуется, чтобы на кнопку отправки формы нельзя было нажать, пока не заполнены все поля этой формы. Проще всего заблокировать кнопку атрибутом disabled . Но недостаточно просто указать его в HTML, нужно ещё и при помощи оформления показать пользователю, что кнопка не активна. Как раз для этого нам пригодится псевдокласс :disabled .

Кнопка будет полупрозрачной:

 button:disabled  opacity: 0.5;> button:disabled  opacity: 0.5; >      

Псевдокласс :enabled , наоборот, поможет стилизовать все доступные для взаимодействия элементы. По факту его чаще всего не указывают, потому что записи с ним и без него, как правило, равноценны: .input = .input : enabled .

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Любому селектору, указывающему на интерактивный элемент, дописываем двоеточие и указываем одно из ключевых слов: enabled или disabled .

Как понять

Скопировать ссылку «Как понять» Скопировано

Браузер ориентируется на атрибут disabled и, в зависимости от его наличия или отсутствия, добавляет элементу состояние enabled — доступен, или disabled — недоступен.

Подсказки

Скопировать ссылку «Подсказки» Скопировано

💡 Даже если дизайнер забыл про неактивное состояние, обязательно прописывайте его в стилях, чуть приглушая фоновый цвет или делая элемент полупрозрачным — чтобы пользователь точно знал, что с этим элементом взаимодействовать нельзя.

💡 enabled чаще всего не используется, потому что все интерактивные элементы по умолчанию доступны (включены). Это значит, что прописав стили для селектора .input , вы закрываете сценарий с активным элементом.

На практике

Скопировать ссылку «На практике» Скопировано

Алёна Батицкая советует

Скопировать ссылку «Алёна Батицкая советует» Скопировано

🛠 «Выключать» взаимодействие с кнопками или другими элементами формы удобнее именно атрибутом disabled , потому что он сразу же отключает возможность нажать на этот элемент без дополнительных стилей. И, ориентируясь на него, гораздо удобнее прописывать стили для неактивных элементов, используя псевдокласс disabled .

Код для кнопки из моего последнего проекта:

Стили для активной кнопки в обычном состоянии:

 .additional-btn  padding: 2rem 3rem; border: 1px solid currentColor; font-family: inherit; font-size: 1.6rem; color: #FF6650; text-decoration: none; background-color: transparent; transition: border 0.3s, color 0.3s; cursor: pointer; user-select: none;> .additional-btn  padding: 2rem 3rem; border: 1px solid currentColor; font-family: inherit; font-size: 1.6rem; color: #FF6650; text-decoration: none; background-color: transparent; transition: border 0.3s, color 0.3s; cursor: pointer; user-select: none; >      

Стили для кнопки при наведении курсора или клике:

 .additional-btn:active,.additional-btn:hover  color: #FF5050; transition: none;> .additional-btn:active, .additional-btn:hover  color: #FF5050; transition: none; >      

Стили для кнопки, когда она неактивна:

 .additional-btn:disabled  cursor: default; color: #A44234;> .additional-btn:disabled  cursor: default; color: #A44234; >      

Источник

:disabled

CSS псевдокласс :disabled находит любой отключённый элемент. Элемент отключён, если не может быть активирован (например, его нельзя выбрать, нажать на него или ввести текст) или получить фокус. У элемента также есть включённое состояние, когда его можно активировать или сфокусировать.

Примеры

Пример селекторов

Выберет все отключённые поля ввода

Найдёт все отключённые select элементы с классом country

Пример использования

input[type="text"]:disabled  background: #ccc; > 

Применим к этому HTML5 фрагменту:

form action="#"> fieldset> legend>Адрес доставкиlegend> input type="text" placeholder="Имя"> input type="text" placeholder="Адрес"> input type="text" placeholder="Почтовый индекс"> fieldset> fieldset id="billing"> legend>Адрес оплатыlegend> label for="billing_is_shipping">Такой же как адрес доставки:label> input type="checkbox" onchange="javascript:toggleBilling()" checked> br /> input type="text" placeholder="Имя" disabled> input type="text" placeholder="Адрес" disabled> input type="text" placeholder="Почтовый индекс" disabled> fieldset> form> 

Добавим немного javascript:

function toggleBilling()  var billingItems = document.querySelectorAll('#billing input[type="text"]'); for (var i = 0; i  billingItems.length; i++)  billingItems[i].disabled = !billingItems[i].disabled; > > 

Результатом будет отключение всех полей в группе адреса оплаты и окраска их в серый цвет.

Спецификации

Поддержка браузерами

BCD tables only load in the browser

Смотрите также

Found a content problem with this page?

This page was last modified on 14 февр. 2023 г. by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

How to Disable an Input Field Using CSS?

The input field is used to make forms and take input from the user. Users can fill the input field according to the input type. But sometimes, you must disable the input field to fulfil any precondition, such as selecting a checkbox. In that situation, you need to disable the input field.

In this guide, we will gain an understanding of how to disable the input field using CSS. So, Let’s begin!

How to Disable an Input Field Using CSS?

In CSS, events are disabled by using the “pointer-events” property. So, first, learn about the pointer-events property.

What is “pointer-events” CSS Property?

The “pointer-events” control how the HTML elements respond or behave to the touch event, such as click or tap events, active or hover states, and whether the cursor is visible or not.

Syntax
The syntax of pointer-events is given as follows:

The above mention property takes two values, such as “auto” and “none”:

  • auto: It is used to perform default events.
  • none: It is utilized to disable events.

Head towards the given example.

Example 1: Adding an Input Field Using CSS

In this example, firstly, we will create a div and add a heading and input field to it. Then, set the input type as “text” and set its value as “Enter Your Name”.

After that, move to the CSS and style the div by setting its background color as “rgb(184, 146, 99)” and height as “150px”.

The output of the above-described code is given below. Here, we can see that our input field is currently active and is accepting the input from the user:

Now, move to the next part in which we use the value of the “pointer-events” property as “none”.

Example 2: Disabling an Input Field Using CSS

We will now use “input” to access the element added in the HTML file and set the value of pointer-events as “none”:

Once you implement the above-stated property “pointer-events” with “none” value, the text of the input field will be non-editable which indicates that our input field is disabled:

That’s it! We have explained the method of disabling the input field using CSS.

Conclusion

To disable an input field in an HTML, the “pointer-events” property of the CSS is used. To do so, add an input field, and set the value of pointer-events as “none” to disable the input field. In this guide, we explain the method of disabling an input field using CSS and provide an example of it.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.

Источник

:disabled¶

Псевдо-класс :disabled находит любой отключенный элемент.

Элемент отключен, если не может быть активирован (например, его нельзя выбрать, нажать на него или ввести текст) или получить фокус. У элемента также есть включенное состояние, когда его можно активировать или сфокусировать.

Синтаксис¶

/* Selects any disabled */ input:disabled  background: #ccc; > 

Спецификации¶

Примеры¶

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
form action="#"> fieldset id="shipping"> legend>Shipping addresslegend> input type="text" placeholder="Name" /> input type="text" placeholder="Address" /> input type="text" placeholder="Zip Code" /> fieldset> br /> fieldset id="billing"> legend>Billing addresslegend> label for="billing_is_shipping">Same as shipping address:label> input type="checkbox" id="billing-checkbox" checked /> br /> input type="text" placeholder="Name" disabled /> input type="text" placeholder="Address" disabled /> input type="text" placeholder="Zip Code" disabled /> fieldset> form> 
input[type='text']:disabled  background: #ccc; > 
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Wait for the page to finish loading document.addEventListener( 'DOMContentLoaded', function()  // Attach `change` event listener to checkbox document.getElementById('billing-checkbox').onchange = toggleBilling >, false ) function toggleBilling()  // Select the billing text fields var billingItems = document.querySelectorAll('#billing input[type="text"]') // Toggle the billing text fields for (var i = 0; i  billingItems.length; i++)  billingItems[i].disabled = !billingItems[i].disabled > > 

Источник

CSS :disabled Selector

Set a background color for all disabled input elements of type=»text»:

More «Try it Yourself» examples below.

Definition and Usage

The :disabled selector matches every disabled element (mostly used on form elements).

Browser Support

The numbers in the table specifies the first browser version that fully supports the selector.

CSS Syntax

More Examples

Example

Set a background color for all disabled elements:

Example

Set a background color for all disabled elements:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Примеры линейных алгоритмов javascript
Оцените статью