pencilCake
pencilCake

Reputation: 53263

div#myID { } vs #myID div { } / Which CSS syntax is recommended?

Are those CSS selectors do the same or there are differences?

div#myID {  }  

#myID div {   } 

If they are the same, which one is recommended?

Upvotes: 0

Views: 997

Answers (7)

SLaks
SLaks

Reputation: 887807

Your selectors are completely different.

The first one combines two different selectors to match every element which is both div and #myID — every <div> with ID myID.

The second one uses the descendant combinator to match all divs which are inside of #myID — every <div>s inside of an element with ID myID.

Upvotes: 4

Spudley
Spudley

Reputation: 168755

The two syntaxes are both valid, but do different things.

div#myID will select a <div> which has the ID of myID.

#myID div will select a <div> which is contained inside another element (of any type) which has the ID of myID.

To give an example, using the following HTML code:

<div id='myID'>
  <div id='somethingElse'>
  </div>
</div>

With the first selector, you will select the outer div above. With the second selector, you will select the inner of the two divs.

Hope that helps.

Upvotes: 2

perdian
perdian

Reputation: 2843

They aren't the same!

div#myID

applies to this:

<div id="myID">
</div>

#myID div does not apply to the example above, but to the text inside the following div container:

<p id="myID">
  <div>
  </div>
</p>

Upvotes: 1

wsanville
wsanville

Reputation: 37516

The first selector will apply to a div with the ID of myID.

The second will apply to all div tags within an element with an id of myID. This is clearly different.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816790

Well, they both do something different, so there is nothing to recommend.

  • div#myID selects a div with ID myID. This can be expressed shorter with just #myID.

  • #myID div selects all divs that are descendants of the element with ID myID.

Upvotes: 3

Mark Coleman
Mark Coleman

Reputation: 40863

div#myID { } will only target a div with the id of myId

#myID div { } will target child divs with an id of myId

Upvotes: 0

Loktar
Loktar

Reputation: 35319

#myID div { }

Styles divs that come after #myId

div#myID {  }  

Styles a div with the id of #myId

It depends on what your trying to achieve in order to suggest which one you should use.

Upvotes: 1

Related Questions