Good practice with css selectors

Asked

Viewed 114 times

5

What is the best practice for working with css selectors?

Use

.menu li { }
ou 
.item {} 
.menu .item { }
ou
.menu-item { } //aqui usamos para atribuir propriedades para as <li> por exemplo

How best practice would be for that ?

2 answers

5


Best practice would be to need less code for everything to work properly, which would not need many classes, but only one parent class accessing the children in this way:

.menu li {
 //codigo
}

So you don’t need to assign a class to your <li>, you can use a longer (more detailed) path if you wish, for example:

.menu > ul > li {
 //codigo
}

Ps: the > are only to indicate a path that is being traveled, are not really necessary, just for understanding.

In your case, remove the class menu-item of <li> and use in the CSS .menu li reduces unnecessary html code, becoming a best practice.

  • 1

    The difference between using and not using > is that in any case descending of .menu whatever li is affected, while in the other the li must be son of a ul who in turn is the son of .menu. Just clearing up...

3

The first option seems to me to be best practice, for the following reason:

  1. .menu li

    Here you have a specific element (or type of elements) in which you want to assign a style to all its sub-elements of type li. For this, just give the class menu its element and automatically all its lis gain the desired style.

  2. .menu .item

    This forces you to add the class item to each of its lis besides add the class menu. If you forget to give this class to any item in the list, this item will have a different style. Unless this is by design (for example, if you want to highlight some element), it is a reductive information.

  3. .menu-item

    Similar to the item above, it just relieves you of having to create the class menu. But the problem of multiples liEach one with his class remains.

P.S. While writing this, @Paulo Roberto added an answer that sums it up perfectly:

Best practice, would need less code for everything to work properly

Browser other questions tagged

You are not signed in. Login or sign up in order to post.