HTML & CSS
Article

AtoZ CSS Screencast: Enabled Pseudo-class

By Guy Routledge

Loading the player…

This screencast is a part of our AtoZ CSS Series. You can find other entries to the series here.

Transcript

I’ve got two sets of inputs and buttons here.

They are both in their default state of enabled which we can demonstrate by styling them with the :enabled pseudo-class, giving them a dark gray background and a blue text color.

If I now add the disabled attribute to the HTML of the first set of inputs, the user agent styles for disabled fields takes over and our :enabled styles do not as the inputs are no longer enabled. We can control the styling of disabled inputs in CSS with the :disabled pseudo-class.

Use case

Let’s take a look at a real-world use case.

Here we have the payment step for ordering some food online. In this stage of the form, the payment method is requested, and the choice is either cash or card.

If we want to pay by card, the fields for the card holder, card number, start date, expiry date and security code are enabled. If we want to pay with cash, these details aren’t needed, and we can disable them. This can’t be done with CSS alone, but we can use a bit of JavaScript or jQuery to handle the interaction.

When we change the payment method, the script checks whether the radio button with the ID of cash is :checked. This is another pseudo-class that determines state – in this case, the checked or unchecked state of a checkbox or radio button. If cash is checked, we add the disabled attribute to all the inputs and select menus in the card fields container. We also add an is-disabled class to the labels which will allow these to be given different styles too.

We can then style these in CSS, making the color of the text and the background of the inputs a light gray to show that they’re no longer enabled.

Watch out for our Quick Tip article coming soon!

More:

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in Front-end, once a week, for free.