CSS Style Nesting - Proper Form?

If you include more parents, it does increase selector specificity. You shouldn't have cross-browser problems omitting parents.

There is no correct number of parents to list; it depends on what you require for your markup. As you're seeing, selector1 selector2 means a selector2 at any level inside a selector1, and you can tune that for whatever behavior you need.

In your example, you should list .mainbody #container #header #toprightsearch .searchbox if what you mean is for the style to only apply to .searchboxes that are inside that entire hierarchy. If contrariwise you want .searchboxes that exist other under conditions to get the same style, you should be less restrictive in the hierarchy. It's only about what you're trying to accomplish.

Re comment: IDs produce more specificity, so omitting them reduces your rule's specificity more.


Id's are specific to the page. So you'd just use

#toprightsearch {
 stylename: stylevalue;
}

If your looking for nested classes then the correct format is

.header .textBoxes {
  stylename: stylevalue;
}

If you know the exact child of a parent then you use the > sign. So if your document was like this:

<div class="header">
    <div class="menu">
         <input type="text" class="textBox" />
    </div>
</div>

You can use this:

 .header > .menu > .textBox {somestyle:somevalue;}

This means only items with a .textBox class directly inside of a .menu class item which is itself directly below an element with a class of .header.


.searchbox {}

Styles anything with .searchbox

.mainbody .searchbox{}

Styles any .searchbox that descends from any .mainbody, direct child, grandchild, quadruple great grandchild, doesn't matter.

#toprightsearch > .searchbox {}

Styles only .searchboxes that are direct children of #toprightsearch

#container * .searchbox {}

Styles .searchbox's that are grandchild or later of #container.

Here's a good document on the topic: w3C selectors

Tags:

Css

Nested