Not active button css

Состояния кнопок

Любая кнопка, если она не заблокирована, может находиться в определённых состояниях, которые связаны с соответствующими псевдоклассами:

Далее рассмотрим эти состояния подробнее.

Активная кнопка

Это состояние возникает, когда на кнопку нажали, но ещё не отпустили (через клавишу мыши или палец на смартфоне). Для изменения стиля активной кнопки к селектору button или соответствующему классу добавляется псевдокласс :active. Его задача показать пользователю, что кнопка прореагировала на нажатие.

В примере 1 к кнопке добавлена тень через свойство box-shadow. У псевдокласса :active тень убирается, а сама кнопка сдвигается вниз и вправо на величину тени. Тем самым при щелчке по кнопке возникает эффект её утопления.

Пример 1. Использование :active

Плавность «хода» кнопки достигается через свойство transiton, которое устанавливает время анимации. Если это свойство убрать из кода CSS, то кнопка будет смещаться мгновенно.

Фокус

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

Кнопка обычно получает фокус, когда на клавиатуре несколько раз нажимают клавишу Tab , по очереди переходя от одного элемента к другому. Вокруг кнопки с фокусом по умолчанию отображается синий контур (рис. 1).

Кнопка, получившая фокус

Рис. 1. Кнопка, получившая фокус

Используя псевдокласс :focus и добавляя его к селектору button или соответствующему классу, можно установить стиль кнопки с фокусом. В примере 2 вокруг кнопки добавляется контур жёлтого цвета через свойство outline.

Пример 2. Использование :focus

Если вместе с псевдоклассом :focus добавляется :active , то для правильной работы важно сохранить их порядок в коде CSS:

Кнопка при наведении курсора

Псевдокласс :hover отвечает за стиль кнопки при наведении на неё курсора мыши. У кнопки таким образом допустимо менять цвет фона, текста и другие параметры. Сама смена происходит мгновенно и для плавности можно добавить свойство transition, указав желаемое время перехода. В примере 3 при наведении на кнопку у неё плавно, в течение полсекунды, меняется цвет фона с тёмного на жёлтый.

Пример 3. Использование :hover

Свойство transition у класса .btn работает в обе стороны — цвет фона меняется плавно при наведении на кнопку курсора и при его уведении. Если transition перенести из класса .btn в селектор .btn:hover , то при наведении на кнопку цвет фона будет меняться плавно, а при уведении вернётся к исходному значению резко.

При наличии других псевдоклассов опять же важен их порядок в CSS. :hover идёт всегда первым, затем уже добавляется :focus и : :active .

Читайте также:  Sonic unleashed java rom

Итоги

  • Кнопка может находиться в трёх состояниях: активная кнопка; получившая фокус; на кнопку навели курсор мыши.
  • За стиль активной кнопки отвечает псевдокласс :active.
  • За стиль кнопки, получившей фокус, отвечает псевдокласс :focus.
  • За стиль кнопки, на которую навели курсор мыши, отвечает псевдокласс :hover.
  • Важен порядок написания этих псевдоклассов в CSS. :hover идёт первым, :active пишется последним:
    1. :hover
    2. :focus
    3. :active

Создайте кнопку, чтобы при наведении на неё курсора мыши она меняла цвет фона и рамки (рис. 1). Обратите внимание на следующие моменты:

  • используется жирный шрифт;
  • к тексту добавлена небольшая полупрозрачная тень;
  • у самой кнопки имеется внутренняя тень;
  • время смены цветов установите в полсекунды.

Создайте кнопку, чтобы при наведении на неё курсора мыши она плавно меняла цвет фона и текста, как показано на рис. 1.

Создайте кнопку, чтобы при щелчке у неё исчезала линия снизу и кнопка сдвигалась вниз, как показано на рис. 1.

См. также

  • :focus для полей формы
  • :focus на мобильных устройствах
  • outline
  • outline-color
  • outline-offset
  • outline-style
  • outline-width
  • Анимация ссылок при наведении
  • Виды ссылок
  • Всплывающая подсказка
  • Использование :hover
  • Нормальное позиционирование
  • Переходы с помощью :hover
  • Подсветка строк и колонок таблицы
  • Псевдокласс :active
  • Псевдокласс :focus
  • Псевдокласс :focus-within
  • Псевдокласс :hover
  • Псевдоклассы в CSS
  • Работа с типографикой
  • Свойство border
  • Селекторы CSS
  • Сочетание с псевдоклассами
  • Типы ссылок

Рецепты

Источник

How to disable button with CSS

In this blog post, we will look into “How to disable button with CSS” on a webpage & get into various ascpects relating to it.

Contents

How to disable button with CSS?

Buttons are placed on a webpage to perform some event. When the user clicks it then something happens on that page as per the coded actions by the programmer.

There are certain scenarios that we want to show the button but it will only be clickable after a certain condition is fulfilled. Example is the Login page, we want the user to enter the username & password then he can click the login button to enter within the application. When the details are not yet entered by the user then clicking the button is of no use so it can be kept disabled.

After disabling the button, it will stop performing any action & as a default style it will be grayed out. When the user clicks it, the main event will not be performed.

Disabled buttons can also be styled with the help of CSS styles. We can also change the cursor when the user hovers over the button so that the user can easily understand that the button is disabled.

Let’s walk through the code to disable button with CSS :-

HTML :-

 

Result :-

disable button

background-image property specifying the image to be displayed. It futher sets the width & height of the header element.

How to style disabled button with CSS?

It is necessary to style a disabled button in a proper manner so that user can understand it is disabled. If user is unable to understand he will keep clicking the button & will think there something wrong in this website.

Читайте также:  Nginx rewrite all to index html

Usually the disabled button can be shown as grayed out with a cursor value of not allowed. Different variations of grayed color can be applied as per the preference.

The title text also helps in giving quick information to the user. Title text appears automatically when the user hovers over the button.

The style of the disabled button should be different from the style of the normal buttons. So there can be 2 different set of styles defined in CSS for normal button & disabled button.

Below code is used for styling the disabled buttons :-

CSS :-

button:disabled, button[disabled] < border: 1px solid #999999; background-color: darkgrey; color: #fff; padding: 10px; cursor: not-allowed; >.btn

HTML :-

 

Result :-

style disabled button with CSS

How to disable hover effect when button is disabled CSS?

When the button hover effect is defined in styles then it gets applied to all the buttons. The button may be enabled or disabled the same style applies to both with no difference.

We can modify this default behavior & apply the style only to the enabled buttons on a web page. For the disabled buttons this style of hover effect will not be applied.

Changing the hover effect is necessary for disabled buttons because the users always hover the buttons before clicking it. If the hover effect for disabled button is the same as the enabled button then there will be no difference & disabled button might look like an enabled button.

The style for the disabled button is usually faint. So the hover effect can also be styled to the same pattern to maintain consistency.

Below code displays the style that can disable hover effect of button :-

CSS :-

.btn < border: 1px solid #999999; background-color: blue; color: #fff; padding: 10px; >.btn:hover:enabled < background-color: black; color: #fff; >button:disabled, button[disabled]

HTML :-

 

Источник

Easily Disable a Button with JavaScript or CSS (3 Examples)

We should also lighten the button’s opacity by about 33% (like Bootstrap’s disabled class does). In this post, I will show full JavaScript and CSS code for disabling HTML buttons.

Disable Buttons with JavaScript and CSS

Finally, make sure the button cannot be tabbed into and that the button is disabled for screen readers. We’ll see how to do that below.

The Resources section has a live Code Sandbox demo link.

In these examples I applied the following styling to my button elements:

Simple JavaScript Code for Disabling an HTML Button

Here are the steps for disabling a button with JavaScript:

  • Select the button using document.getElementById, document.querySelector, or your preferred method
  • Attach a click event listener
  • Set the disabled attribute to false in the click handler (this requires a reference to the button)

It is important to pass a reference to the button into the click handler. Take a look at the below code to see how I accomplished this:

//HTML Button  //JS Click Event Listener const jsDisableButton = document.getElementById("jsDisableButton"); if (jsDisableButton) < jsDisableButton.addEventListener("click", () =>handleJSBtnClick(jsDisableButton) ); > //JS Click Handler const handleJSBtnClick = (jsDisableButton) => < jsDisableButton.disabled = true; console.log("JS Disabled"); >;

This code gets the job done, but I recommend some basic styling on the button when it is disabled:

Читайте также:  Python input syntax error

The above selector queries for the disabled pseudo class on button elements.

This styling is important because the opacity gives visual indication that the button is unclickable. Removing pointer events keeps hover and click events from occurring. If we only set cursor: default; then the cursor looks inactive but hover and click events can still occur.

You also have the option of passing the click event to the handler. Here’s what the updated code looks like (with TypeScript):

const jsDisableButton = document.getElementById( "jsDisable" ) as HTMLButtonElement; if (jsDisableButton) < jsDisableButton.addEventListener("click", (event: MouseEvent) =>handleJSBtnClick(event, jsDisableButton) ); >

CSS Styling for Disabling an HTML Button

We can set a couple of style properties on a button to effectively make it disabled without using the disabled attribute.

The most basic property is pointer-events: none; . This makes the element unable to register clicks or hovers. I also recommend reducing the opacity so the button renders as a lighter color.

.disabled < pointer-events: none; opacity: .65; >//HTML 

These can easily be applied using a class on the element.

You may have noticed that I recommended adding both of these styles in the previous section where we set the button attribute disabled=true . Styling with these properties is good practice on any disabled button.

One disadvantage of using a CSS approach is that users can still tab in to the button and ‘click’ it by pressing enter . Interestingly, this first triggers a keypress event and then triggers a click event.

The two solutions to this are setting tabindex to -1 or adding a keypress event listener and preventing the default behavior. Both are described below.

Programmatically Disable Button with CSS Class

Toggling a CSS class on an HTML button element is similar to toggling the disabled attribute.

Once again, we select the button and attach a click event listener. Then in the click handler we need to add the disabled class using classList.add(«disabled») .

  const handleCSSBtnClick = ( event, cssDisabledButton ) => < cssDisabledButton.classList.add("disabled"); console.log(event); >; const cssDisabledButton = document.getElementById("cssDisable"); if (cssDisabledButton) < cssDisabledButton.addEventListener("click", (event) =>< handleCSSBtnClick(event, cssDisabledButton); >); cssDisabledButton.addEventListener("keypress", (event) => < event.preventDefault(); >); >

I also included the code for adding a keypress listener in case the user tabs into the button and presses enter . Later I will show how to eliminate tabbing.

Disabled Button ARIA Considerations

Users requiring screen readers and non-mouse users need to be supported when a button is disabled.

Screen readers need the aria-disabled attribute to be set to true on the button. This indicates that the element is perceivable but not operable, according to MDN.

Next, the tabIndex attribute needs to be set to -1 while the button is disabled. This keeps users from tabbing into a disabled element and interacting with it through the keyboard.

Here’s an example button that has both attributes set.

Resources

Code Sandbox Link (This includes TypeScript as well)

Источник

Оцените статью