Displaying the Current Step with CSS Counters

Displaying the Current Step with CSS Counters

css-tricks.com css-tricks.com2 years ago in #Dev Love46

Say you could have 5 buttons. Each button is a step. If you click on on the fourth button, you’re on step four of five, and you need to show that. This roughly counting and showing might be hard-coded, however that’s no amusing. JavaScript may just do that task as neatly. But CSS? Hmmmm. Can it? CSS has counters, so we will be able to surely depend the choice of buttons. But how can we calculate simplest as much as a definite button? Turns out it may be executed. Thanks to Jan Enning for emailing in about this trick, it’s very artful! HTML It doesn’t should be buttons; it simply must be some sibling parts we will be able to depend. But we’ll move forward and use buttons right here: Shop Cart Shipping Checkout Thank You The empty .message div there can be the place we output our step messaging with CSS content material. CSS The trick is that we’re in fact going to make use of 3 counters: A complete depend of all the buttons A depend of the present step A depend of what number of final steps are after the present step .steps { counter-reset: presentStep 0 the rest 0 overallStep 0; } Now let’s in fact do the counting. To depend all buttons is simple: button { counter-increment: overallStep; } Next, we’d like some other factor to depend that can even depend the buttons. We can use a pseudo-element that’s simplest objective is to depend buttons: button::earlier than { content material: “”; counter-increment: presentStep; } The trick is to prevent counting that pseudo-element on all the parts after the energetic detail. If we’re the use of an .energetic elegance that appears like this: button.energetic ~ button::earlier than { /* prevents presentStep from being incremented! */ counter-increment: the rest; } We’re counting the the rest there, which may also be helpful, however as a result of we’re simplest incrementing the the rest, that suggests we’re now not counting the presentStep counter. Fancy, fancy. Then we will be able to use the counters to output our messaging: message::earlier than { content material: “Step: ” counter(presentStep) ” / ” counter(overallStep); } Here it’s! There is somewhat JavaScript there so you’ll play with transferring the energetic state on the button, however the counting and messaging is all CSS.  » Read More

Like to keep reading?

This article first appeared on css-tricks.com. If you'd like to keep reading, follow the white rabbit.

View Full Article

Leave a Reply