Covar
Covar

Reputation: 900

What is the difference between ".class element" and "element.class"?

Is there a difference between .class element and element.class in a CSS selector?

I had always been shown element.class but just the other day came across a CSS file at work that had .class element and wanted to know if this was just a style choice (in which case I would make my changes match), or if there was a specific reason (in which case I would not necessarily want to make my changes match).

Upvotes: 46

Views: 22699

Answers (4)

FreeFog
FreeFog

Reputation: 21

I like to think it as follows:

1) a, b  =   a OR b
2) a  b  =   a AND b (on that order)
3) a.b   =   a.b     (on that order)

2, 3) a b is not the same as b a.
2) Elements belonging to a and b simultaneously, i.e. nor a or b elements. Is a range selection.
3) a elements of b class. Is an exact selection.

Upvotes: 1

danmak
danmak

Reputation: 1

very simple example:

HTML:

<ul class="a">
<li>1</li>
<li class="a">2</li>
<li>3</li>
</ul>

CSS:

.a li{color:blue;}
li.a{color:red;}

Upvotes: -3

glortho
glortho

Reputation: 13200

element.class selects all <element />s with that class. .class element selects all <element />s that are descendants of elements that have that class.

For example, HTML:

<div class='wrapper'>
  <div class='content'></div>
  <div></div>
  <div class='footer'></div>
</div>

For example, CSS:

div.wrapper {
  background-color: white; /* the div with wrapper class will be white */
}

.wrapper div {
  background-color: red;   /* all 3 child divs of wrapper will be red */
}

Upvotes: 60

Doug Stephen
Doug Stephen

Reputation: 7351

"element.class" selects elements that have the given class.

".class element" selects all elements that are children of anything with the given class.

Example:

<div class="foo">
    <p>...</p>
</div>

div.foo would select the div, while .foo p would select the child paragraph. It should be noted that without specifying direct child via the ">" selector, this will traverse the entire document tree when looking for children.

Upvotes: 13

Related Questions