Use a class or elemets tag to style them

Which is the right way to style different elements in a document:

Class:

<style>
        .red {
            color: red;
        }
    </style>

    <h1 class="red">Hello, world!</h1>
    <p class="red">This is some text.</p>

HTML tags:

<style>
        h1,
        p {
            color: red;
        }
    </style>

    <h1>Hello, world!</h1>
    <p>This is some text.</p>

There is no right or wrong way but it does depend on context and maintainability.

If you want all p elements in your document to be red then the ‘p {color:red}’ is fine. However, it is 99% unlikely that you would want all p elements in the document to be red and thus you would spend more time ‘undoing’ those rules and they would have been better defined with a class.

If you have a narrow context such as inside a header then you could say #header p{color:red} and that would likely be ok until one day you add a new p element and it gets turned red when you didn’t expect (or third party code is used in the header and that gets styled inadvertently). If you know the context is never to change then descendant selectors are fine but for a more modular approach adding a simple class is more foolproof although it does result in using more classes.

As, I said above there is no ‘right way’ as such but it does depend on context.

On large or dynamic sites with regularly changing content it is often easier to “class” elements rather than target then by position (descendant selectors) and you can be sure that adding or removing items won’t affect the styling. It’s more of a modular approach and makes maintenance easier in the long run although there is some excess code overhead.

As a rule of thumb if you find yourself ‘undoing’ styles you have applied a little too often then you are most likely not doing it in the most efficient way.

1 Like

Either way will work.

The class name option is more OOP as it’s more separation between the structure and the styling.

Very educational! Thank you! :slight_smile:

1 Like