Forum Moderators: not2easy

Message Too Old, No Replies

h1.header versus .header h1 - What's The Difference?

         

Planet13

5:00 pm on Nov 3, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Hey everyone:

I am stumped about this:

What's the difference between:

element.class


and

.class element


For example, don't these do the same thing?

h1.header


and

.header h1


Thanks in advance.
~~~~~

Bonus question:

Does the same thing hold true when using IDs instead of classes?

h1#header


and

#header h1

brandozz

5:10 pm on Nov 3, 2014 (gmt 0)

10+ Year Member



No, they are not the same.

h1.header selects h1 elements with the class "header":

<h1 class="header"></h1>

.header h1 selects the h1 element within an element that has a class "header":

<div class="header">
<h1></h1>
</div>

Fotiman

5:30 pm on Nov 3, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




Does the same thing hold true when using IDs instead of classes?

brandozz's answer applies in the case of IDs as well.
h1#header selects h1 elements with the id "header":
<h1 id="header"> </h1>

#header h1 selects the h1 elements within an element that has an id of "header":
<div id="header">
<h1> </h1>
</div>

Planet13

5:36 pm on Nov 3, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Thanks Very Much!

Very clear and concise.

~~~~~

So I guess that means that in MOST cases, I can use either:

<div class="header">
<h1>something</h1>
</div>

and it would be the same thing as using:

<div>
<h1 class="header">something</h1>
</div>

And they would look the same just as long as I used the correct element.class or the class. element CSS, right?

Fotiman

5:45 pm on Nov 3, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Correct. In both cases you're selecting the h1 element(s) that match the selector.

lucy24

11:34 pm on Nov 3, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



... except that div.header is only meaningful if there's other stuff inside the div and you also want to apply special styles to this other stuff:
div.header h1
div.header p
div.header p.extra
div.header .classname
If the only thing that will ever have special styling is the h1 itself, it's more appropriate to apply the class/id name directly to h1. Less work for the browser and easier for you to keep track of.

If you want to hedge your bets, you can say
.header h1, h1.header {style-stuff-here}


In stylesheets, the class
.name-here
and id
#name-here
are exactly the same in every respect. The only difference is in the HTML: you can have lots of things with a given class, but only one with a given id.

Planet13

12:45 am on Nov 4, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Thank you all, brandozz, Fotiman, and lucy24!