strainer
strainer

Reputation: 627

What is appropriate ordering of css selector? eg p.class or .class p

While debugging some css i noticed there is a difference between this order of declaration. The first caused headings inside anchors to display inline as desired, the second seems not to:

1/ a.aname { display:inline; margin:0px;}
2/ .aname a { display:inline; margin:0px;}

<a name="download" class="aname"><h2>Download</h2></a>

I have mostly been using the second form to apply class styles. What is the difference in how these are applied, and are there any guide rules when to use each? (to avoid the css-puzzlement which arises when it's done wrong)


Basic solution from answers:

Use "direct selection" elementtype.class{} or elementtype#id{} to apply style to elements directly. For styling which is intended to affect once each time the rule is used eg. a margin change, a display change, a noninheriting font change. Direct selection does not inherit to child elements, it is applied to parent element only.

Use "descendant selection" .class elementtype{} or #id elementtype to apply style to type descendants/children of the named or classed element. For styling which is intended to change appearance of elementtypes under an element/within a section of page where it is applied eg. inheriting font changes to text sections, inheriting format changes to paragraphs or list elements. Descendant selection applies to all child elements but never the parent.

NBself: learn about other selectors too asap ;)

Upvotes: 3

Views: 4812

Answers (1)

Guffa
Guffa

Reputation: 700342

The difference is the space between them, which is the descendant combinator in CSS.

The selector a.aname will match an anchor element with the class aname while the .aname a will match an anchor element that is a descendant of an element with the class aname:

<a class="aname">This matches the first rule</a>

<span class="aname"><a>This matches the second rule</a></span>

CSS combinators:

space = descendant combinator

> = child combinator (direct descendant)

+ = adjacent sibling combinator

The Selectutorial gives a pretty good overview or selectors and combinators.

If you use selectors where you can put identifiers together without combinators between them, the order doesn't matter. Example:

#id.class { ... }
.class#id { ... }

Upvotes: 14

Related Questions