Why is a class attribute necessary when centering a table?

New to the forums here, as well as HTML and CSS. In working on a project page for myself, I’ve got a table. Reading around how to center it, I went with something like this:

<table class="center">

And then

table.center {
    margin-left: auto;
    margin-right: auto;
}

My question is why is a class used to center here? Couldn’t I just do:

<table>

and then

table {
    margin-left: auto;
    margin-right: auto;
}

I’ve tried this code, and it works, so I’m guessing the browser is covering for me here because I have not seen this applied anywhere. What am I not understanding here? I apologize in advance for the painfully noobish question. I did search the boards a bit for this exact question. Thanks much!

Answer

It’s a case of convention. They both work; but it’s better to segregate your styles into only the elements that need it. Without using a class then the style will apply to all tables, which may not be the case for all pages and is generally considered bad practice.

Oftentimes the same style sheet will be used on multiple pages of a site for consistency – so it’s better to select only certain tables rather than all – as it might not be the case that you want all tables on all pages to look the same. This doesn’t just apply to center styles, it applies to all.

Leave a Reply

Your email address will not be published. Required fields are marked *