Good practice with selectors in css

5

What is the best practice for working with selectors in css?

Use

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

What would be the best practice for this?

    
asked by anonymous 19.03.2014 / 18:23

2 answers

5

Best practice, would be to require less code so that everything works correctly, which would not require many classes, but only one parent class accessing the children in this way:

.menu li {
 //codigo
}

So you do not need to assign a class to your <li> , you can use a longer (more detailed) path if you want, for example:

.menu > ul > li {
 //codigo
}

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

In your case, removing the menu-item class from the <li> and using it in% .menu li reduces unnecessary html code, becoming a best practice.

    
19.03.2014 / 18:29
3

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

  • .menu li

    Here you have a specific element (or element type) in which you want to assign a style to all its sub elements of type li . To do this, simply give the class menu to your element and automatically all your li s get the desired style.

  • .menu .item

    This forces you to add the item class to each of your li s in addition to add the menu class. If you forget to give this class some 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's redistant information.

  • .menu-item

    Similar to the above, it only relieves you from having to create the menu class. But the problem of multiple% s with each class remaining.

  • P.S. While writing this, @Paulo Roberto added an answer that summarizes this perfectly:

      

    Best practice, would be to need less code to make everything work correctly

        
    19.03.2014 / 18:31