Repeating Classes
Look at the four Adopt buttons in the cats' cards. Each of them has a list of nine classes, and the lists should be the same:
<a href="#" class="mt-4 inline-block rounded-full bg-brand-500 px-5 py-2 font-semibold text-white hover:bg-brand-600">Adopt Tiger</a>That's the Tailwind way: every element says how it looks, right in the HTML. Most of the time, it's an advantage. You see how an element looks where the element is, and when you change one element, you can't break another one by accident. But when an element repeats, its list of classes repeats with it. When the shelter wants different buttons, you have to change all four lists in the same way. And if you miss one, that button looks different from the others. It has already happened on our page: someone changed the buttons' corners from rounded-lg to rounded-full and missed one button. Look closely at the preview.
What can you do about it?
- Write the element only once. Real websites are rarely written by hand, card by card. The list of cats would come from a database, and the card would be written only once, in a template or a component (a reusable piece of a page, as in JavaScript frameworks such as React). The code would then repeat it for every cat. That way, its classes are in one place too. This is the solution that Tailwind's authors recommend first.
- Edit all the places at once. When the repeated elements are close together, like our four buttons, you can simply change them all. Code editors help with that, and so does this one: select a piece of text and press
Ctrl+D(on a MacCmd+D), and the next place with the same text gets selected too. Each press adds the next one. Whatever you type then goes into all the selected places at once. - Give the list of classes a name. When neither of these helps, Tailwind lets you make your own class from a list of its classes. You'll learn how in the next exercise.
Instructions
Find the Adopt button whose corners are different from the others, and in index.html, give it rounded-full instead of rounded-lg, like the other three.
Now change all four Adopt buttons at once: add the class transition-colors to the end of each of their lists. When the mouse moves over a button, its color will now change smoothly. (Tip: in Tiger's button, select hover:bg-brand-600, press Ctrl+D three times and then the right arrow key, so that there's a cursor after each of the four, and type a space and transition-colors.)
Start programming for free
3/7