Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason not to use a single non-nested class name as CSS selector?

If I have a container and a list of item, I might have the following HTML markup:

<div class="container food foodcontainer">
    <ul class="list foodlist">
        <li class="listitem fooditems"></li>
        ...

And I can style them two ways (assuming using plain CSS and not less/sass or any other helpers). First, like one normally would do:

.food { /* style */ }
.food .list { /* style */ }
.food .list .listitems { /* style */ }

Or, I can simply reference everything by a verbose, descriptive class name:

.foodcontainer { /* style */ }
.foodlist  { /* style */ }
.fooditems  { /* style */ }

No more cascading relationships! Is there a reason not to do this for everything (such that every element is referenced by a single class/id name)? I (and people working on the same codebase) simply do not find either to be that much better in readability; if anything, we find unique and direct names easier to grasp and also easier to search for.

There was an ancient article that generally recommended shorter, more unique selectors, for performance; in its more recent update, it's said that overall the performance has changed for the better. But how much better? Is the shorter way still faster?

like image 486
Alexander Chen Avatar asked Oct 19 '22 10:10

Alexander Chen


1 Answers

.food .list { /* style */ } targets only elements with list class that are within an element with a class food.

.food > .list { /* style */ } targets only elments with list class that are direct children of elements with a class food.

.list { /* style */ } targets any elements with the class list, regardless of their parent elements.

Generally, if you want to make sure you're only targeting an element within a specific element and not any other elements that might have the same class, use the first or the second of the above, depending on your needs.

Of course, you could also give unique classes to them to avoid chaining them, but IMO there's just an unnecessary hassle of remembering which classes you've already in use. Also, I think it helps with readability, when you chain them instead of coming up with unique classes - then it's easier to see within which elements these rules apply.

I wouldn't worry too much about the performance with either of those - unless you have massive sites.

You can read about the CSS selectors here.

like image 60
Okku Avatar answered Oct 22 '22 01:10

Okku