Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selectors: (menu ul li) or (menu li)

Tags:

html

css

which is better for use

.menu{
    float:left;
    width:600px;
    height:25px;
    background:url(bg.png) repeat-x;

}
.menu ul{
    float:left;
}
.menu ul li{
    float:left;
    width:150px;
    height:25px;
    background:#F00;
}

or

.menu{
    float:left;
    width:600px;
    height:25px;
    background:url(bg.png) repeat-x;

}
.menu ul{
    float:left;
}
.menu li{
    float:left;
    width:150px;
    height:25px;
    background:#F00;
}

which tag is right menu ul li or menu li?

like image 550
Kali Charan Rajput Avatar asked Dec 10 '22 15:12

Kali Charan Rajput


2 Answers

When you say which tag is right menu ul li or menu li?, are you talking about a div with class="menu" or are you talking about the deprecated menu tag (<menu>)?

If you are just talking about your css code, those are not tags, they are selectors. And I'd go with the most specific selector available in order to avoid accidental assignments

.menu > ul > li{
    // this matches only list items directly inside a ul directly inside a .menu
}

even better would be this:

#menu > ul > li{
    // now you are referencing the menu by id, so you know this is a unique assignment
}

or, if you have multiple menus:

#menubar > .menu > ul > li{
}

because otherwise you are in for surprises, you might actually have a structure like this: (this is ugly, I know, but just to prove a point)

<div class="menu">
    <ul>
        <li>Menu Item 1</li>
        <li>Menu Item 2</li>
        <li>Menu Item 3
        <ul>
            <li id="abc">Menu Item abc</li>
        </ul>
        </li>
        <li>Menu Item 4
        <div><div><div><ol><li><div><ul>
                <li id="xyz">Menu Item xyz</li>
        </ul></div></li></ol></div></div></div>
        </li>
    </ul>
</div>

(you probably don't want to match items abc or xyz).

like image 91
Sean Patrick Floyd Avatar answered Jan 02 '23 07:01

Sean Patrick Floyd


It makes no difference until you have to interact with other, similar selectors in the same stylesheet — and then it depends on what those selectors are.

like image 23
Quentin Avatar answered Jan 02 '23 07:01

Quentin