Getting the Most out of CSS

AID: 2125
  • Status: Published

9040 points

  • ByMageWind
  • TypeGeneral
  • Posted on2009-12-18 at 19:13:42
Awards
  • Community Pick
  • Experts Exchange Approved
Every web designer has heard about and used styles, but they often do not use css as effectively as possible.  Here are some things that you should know in order to make the most out of css.

Before You Start: Doctype
A valid xhtml page must have a doctype declaration.  The DTD (Document Type Definition) specifies the syntax and rules that a webpage follows. If you do not specify a DTD, then a browser does not know how strictly it should stick to the CSS rules, so your site may not display properly.  Below is an example, the HTML 4.01 Transitional doctype:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
                                    
1:

Select allOpen in new window


You should place the correct doctype at the very top of your HTML document (even before the <html> tag). The full list of valid doctypes is here: http://www.w3.org/QA/2002/04/valid-dtd-list.html.

5 Ways to Define a Style
Selectors are the headings that define which elements will have a style.  Below are some different ways to define a selector.

1. Tag
Using css, you can apply a style to all elements with a specific tag.
The following code makes every div tag have a blue background.
div
{
background-color:blue;
}
                                    
1:
2:
3:
4:

Select allOpen in new window


The selector for defining a tag style is simply the tag name.

2. Class
Classes are great if you would like to apply a style to multiple, specific elements.  The following code will make every element with class="favorite" have a blue background.
.favorite
{
background-color:blue;
}
                                    
1:
2:
3:
4:

Select allOpen in new window


The selector for defining a class style is: .classname.
The following will both have a blue background:
<div class="favorite>Here is a div example</div>
<a class="favorite">Here is an anchor example</div>
                                    
1:
2:

Select allOpen in new window


Remember to always have class="classname" in the elements that you want to be styled.

3. ID
You can also apply a style to an element with a specific ID or name.  The following will make the background-color all elements with id="myblue" or name="myblue" blue.
#myblue
{
background-color:blue;
}
                                    
1:
2:
3:
4:

Select allOpen in new window


The selector to define a style for a particular ID is: #id.
If you want only one element on your webpage to have a style, then you should define the style based on the element's id.  However, if you want multiple elements to have a particular style, then you should define the style using classes so that you don't have multiple elements with the same id.  Having more than one element with the same id makes it harder to identify elements when you try to dynamically edit an element.

4. Pseudo-Classes/Elements
Pseudo-classes/elements add additional styles to elements.  The following changes the background-color of an element (even the body) to blue when the mouse hovers over the element.
:hover
{
background-color:blue;
}
                                    
1:
2:
3:
4:

Select allOpen in new window


The selector for defining a style for a pseudo-class/element is: :pseudo_class_name

5. Attribute
You can also define a style for an element with a particular attribute.  The following code would make the background blue for any element with the attribute valign="middle".
[valign="middle"]
{
background-color:blue;
}
                                    
1:
2:
3:
4:

Select allOpen in new window


The syntax for defining a style based on the elements attribute is: [attribute="option"].  You can style an element that has any value for an attrubute using: [attribute].


Combining Selectors
You can add uniqueness to your elements by combining selectors in different ways.

Multiple Selectors in One
You can combine the above ways to make a very specific selector.  The tag name MUST come first, followed by the class, id, pseudo-class/element, or attribute selectors in any order.  Selectors are exclusive, meaning that an element must meet all of the requirements in order for the style to apply to it.  
The following makes the background blue of an element whose class is csstest when the client hovers over the element:
.csstest:hover
{
background-color:blue;
}
                                    
1:
2:
3:
4:

Select allOpen in new window


You could also have written it:
:hover.csstest
{
background-color:blue;
}
                                    
1:
2:
3:
4:

Select allOpen in new window


Here is an example of a more complicated selector:
div.csstest#mydiv[valign="middle"]:hover
{
background-color:blue;
}
                                    
1:
2:
3:
4:

Select allOpen in new window



Grouping
One of the great things about programming is code re-useability.  You can assign one style to multiple selectors.
ul.list, ol.special
{
background-color:blue;
}
                                    
1:
2:
3:
4:

Select allOpen in new window


To group selectors, separate them with a comma.

Nested Elements
You can also combine selectors to apply to certain elements nested inside of another element.

Descendants
The code below will make every span element that is nested inside of any div element have a blue background.
div span
{
background-color:blue;
}
                                    
1:
2:
3:
4:

Select allOpen in new window


The syntax for defining the style of a descendant is: ancestor *space* descendant.  The style will only apply to the descendant, not to the ancestor.
The code above will make the span element below have a blue background.
<div>
  Here is the span: <span>SPAN!</span>
</div>
                                    
1:
2:
3:

Select allOpen in new window


Even if the descendant is not a direct child of the ancestor, it will still have the style.  The span below will also have a blue background.
<div>
  <ul>
    <li><span>Here is the span.</span></li>
  </ul>
</div>
                                    
1:
2:
3:
4:
5:

Select allOpen in new window


You can define as many ancestors as you want.  Below is an example:
div div span
{
background-color:blue;
}
                                    
1:
2:
3:
4:

Select allOpen in new window


The above style will apply to a span that is the descendant of two divs.
You can edit the descendant's and ancestor's selectors for a more specific effect.
ul.nav li:hover ul
{
position:absolute;
left:100%;
visibility:visible;
}
                                    
1:
2:
3:
4:
5:
6:

Select allOpen in new window


The above style could be used as a stepping stone toward making a navigation bar.

Children
You can also define a style for a child, which is an immediate descendant of an ancestor.  The parent is the element that is only one level up from the child.  For example:
<div id="div1">
  Here is span #1: <span>span1</span>
</div>
<div id="div2">
  <ul>
    <li>Here is <span>span2</span></li>
  </ul>
</div>
                                    
1:
2:
3:
4:
5:
6:
7:
8:

Select allOpen in new window


Span1 is a child of div1 because span1 is nested inside of div1 and div1 is only one level up from span1.  On the other hand, span2 is not a child of div2 because span2 is also nested inside of a ul element and a li element.  In fact, span2's actual parent is the li because the li is one level up from span2.
Now consider the following css style:
div > span
{
background-color:blue;
}
                                    
1:
2:
3:
4:

Select allOpen in new window


The syntax for this selector is: parent > child.  If this style were applied to the html before, span1 would have a blue background, but span2 would not.

Siblings
You can also define a style for a sibling, or an element that has the same parent as another element.  The below css code styles the paragraph element that has the same parent as an img element.
img + p
{
background-color:blue;
}
                                    
1:
2:
3:
4:

Select allOpen in new window


The syntax for styling a sibling is: sibling + sibling_to_style.
Now consider the following html:
<div>
  <img src="myimage.jpg" alt="myimage" />
  <p>Here is paragraphA</p>
</div>
<div>
  <p>Here is paragraphB</p>
</div>
                                    
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window


In the above code, the first paragraph element (A) will have a blue background because both it and the img element are nested inside the same div element.  However, the second paragraph element (B) will not have a blue background because its parent does not also have an img child.


*Wildcard*
You can use the wildcard (*) to specify any element.  For example:
div * + ul
{
background-color:blue;
}
                                    
1:
2:
3:
4:

Select allOpen in new window


The above code references any ul that has any type of sibling inside a div element.


Which Style will Win?
Say you have multiple styles that apply to a single element (which is not an uncommon occurrence). How do you know which style(s) will be applied?

Inheritance
Styles will "collapse" into a single style depending on the element.  Consider the following style:
p
{
color:red;
}
.blueclass
{
background-color:blue;
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:

Select allOpen in new window


<p class="blueclass">What color will this paragraph be?</p>
                                    
1:

Select allOpen in new window


The paragraph above will have a red color and a blue background.  Why?  As long as the properties don't conflict with one another, the element inherits each property.

Proximity
But what happens when properties do conflict?  Simply put, the property that is closer to the element will be used.  The order of "proximity" is as follows (from furthest to closest):
1) External style
2) Local style
3) In-line style

Therefore, styles declared using the inline style="property:value" attribute will always override any other style.  Next are the styles declared in the head of the html document using the <style> tag.  External style sheets referenced to the webpage using the <link rel="stylesheet" src="location" /> tag have the lowest priority.

This is why web designers generally put website styles in an external style sheet and page-specific styles in local or in-line styles.  First, it is easier to simply reference to an external style sheet rather than copy the styles into every page a change is made.  Second, element or page-specific styles can override the external style.

Specificity
But say that you have two conflicting styles located in the same place.  Now what happens?
In this case, the importance of the style is calculated using specificity.  Here's how it works:
1) The style with the most id selectors (#id) will take precedence.
2) The style with the most class, attribute, and pseudo-class selectors will take precedence.
3) The style with the most tag selectors will take precedence.
If step one does not resolve the conflict, then the browser moves on to step 2.  If step 2 doesn't work, then it moves on to step 3.
Here's an example:
/* Number 1 */
.classred
{
background-color:red;
}

/* Number 2: */
div ul li a
{
background-color:blue;
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

Select allOpen in new window


At first it appears that number 2 is more specific, but style number 1 is the one that will be used.  Why? Because number 1 has a class definition, but number 2 does not -- it doesn't matter that number 2 has four tag selectors because tag selectors are not as important as class selectors.

The Latter Wins
And what happens if they have the same specificity?  Simply put, the latter style wins.  Whichever style is declared later in the style section will be the style that takes precedence. This is really the same rule as Proximity, but applied within a single style sheet or style block.
.test
{
background-color:blue;
}
.test
{
background-color:red;
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:

Select allOpen in new window


In this case, the element will have a red background.


Conclusion
You can define a style using 5 different types of selectors: by tag, class, id, pseudo-class/element, or attribute.  You can combine these selectors to create more specific and unique styles.  For additional specification, you can declare a style in relation to an ancestor, parent, or sibling.  As your website accumulates more and more styles, you must constantly remember which styles will take precedence over another and how the styles will interact with one another.

I hope you found this article to be useful!  Post a comment if you have any questions or corrections.

Reference:
http://www.w3.org/TR/CSS2/selector.html
http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/
Asked On
2009-12-18 at 19:13:42ID2125
Tags

css

,

cascading style sheet

,

style

,

class

,

stylesheet

,

specificity

,

importance

Topic

Cascading Style Sheets (CSS)

Views
2514

Comments

Expert Comment

by: dhwake on 2009-12-24 at 07:47:54ID: 7320

MageWind,

Thanks for the article.I am pretty new to web design; would you mind explaining the difference between ID and Class div tags?

Author Comment

by: MageWind on 2009-12-27 at 18:55:00ID: 7415

dhwake,

I'd be happy to help you out, but I don't know exactly what your question is.

If you would like to have more than one div tag have a certain style, you should define the style based on class.  The css header for the style will be div.classname.  To select the divs that you want to have the style, put the class="classname" in the div tag.
However, if you would like to have only one div tag have a style, you might want to define the style based on ID.  That way there is no confusion as to which div tag you are styling.  The css header would be div#id.  Make sure you put id="yourID" in the div tag.
Simply, I like to use the id selector to style one specific element and the class selector to style multiple elemnets.

I learned practically everything I know about web design from w3schools.com.  I suggest you explore it a little.

Expert Comment

by: aikimark on 2009-12-27 at 19:51:37ID: 7417

Questions about precedence:
* Does Inheritance trump Proximity?
* Does Proximity trump Specificity?
* Does Specificity trump The Latter Wins?

Expert Comment

by: dhwake on 2009-12-27 at 21:25:07ID: 7420

MageWind,

Thanks, I have used primarily the ID tag, but really wasn't sure what the difference between the two is.

"Simply, I like to use the id selector to style one specific element and the class selector to style multiple elemnets." is what  I was looking for.  Thanks.

Author Comment

by: MageWind on 2009-12-28 at 10:45:35ID: 7442

aikimark,

The browser should resolve conflicts in the order proximity, specificity, then the latter wins.  If the proximities are the same, then the browser looks at the specificity.  If the specificities are the same, then whichever style is declared last will take precedence.
So, in a way
* proximity trumps inheritance
* proximity trumps specificity
* specificity trumps the latter style
Remember that styles "cascade" into a virtual style.  One style doesn't completely "trump" out the others-- they combine.  Precedence comes into play only if there are different values for a particular property (like color).

p
{
color:white;
font-size:2em;
}

div > p
{
background-color:blue;
color:red;
}

------------------------

<div>
<p>
This paragraph will have a red color, a blue background, and a font-size of 2em.  The background-color and font-size properties "cascade", but there are conflicting colors.  The proximities of the two styles are the same (since they're located at the same place), but they have different specificities.  "div > p" is more specific than "p", so the red color trumps the white color.
</p>
</div>

                                        
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:

Select allOpen in new window

Expert Comment

by: mreuring on 2010-03-23 at 12:33:29ID: 11565

@MageWind

Awesome condensed primer on the use of styles! I quickly read through it and gotta say, this is a nice primer that I can use to 'enlighten' some colleagues! They always congratulate me on using my 'magic' this might lift the veil of mysticism a little.

As for proximity/spcificty, inline should probably be highlighted with more emphasis, since it always overrules specificity, while local styles are treated as the 'last stylesheet' so that specificity can still overrule, unless I'm very much mistaken :) That's about the only thing I would change if I were pressed for comments ;)

Author Comment

by: MageWind on 2010-04-01 at 20:58:36ID: 12563

@mreuring

Thanks for the constructive criticism!  I'm always open to suggestions =D  I'm at a bit of a loss, though, as to what you think I should change.  Could you clarify? =)

Author Comment

by: MageWind on 2010-04-01 at 21:00:02ID: 12564

If you liked the article, please say so at the top-right of the article =D

Expert Comment

by: mreuring on 2010-09-07 at 05:00:50ID: 19154

It's been a while since I used EE at all, hope you're still receiving post alert on this article. To clarify what I said before (bold text is what I would recommend adding):

Specificity
But say that you have two conflicting styles located in the same place.  Now what happens?
In this case, the importance of the style is calculated using specificity.  Here's how it works:
0) Inline styles will always overrule stylesheets (<p style="font-weight:bold">). Styles defined using javascript on the style property of an element count as inline styles.
1) The style with the most id selectors (#id) will take precedence.
2) The style with the most class, attribute, and pseudo-class selectors will take precedence.
3) The style with the most tag selectors will take precedence.
***snipped for condensed reply***
The Latter Wins
And what happens if they have the same specificity?  Simply put, the latter style wins.  Whichever style is declared later in the style section will be the style that takes precedence. This is really the same rule as Proximity, but applied within a single style sheet or style block.
Styles defined in a style block within the document are viewed as the 'last added stylesheet' and as such will always be the latter style in equal specificity conflicts.

Still an awesome article though :)

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top CSS Experts

  1. COBOLdinosaur

    213,892

    Guru

    0 points yesterday

    Profile
    Rank: Genius
  2. LZ1

    169,513

    Guru

    0 points yesterday

    Profile
    Rank: Genius
  3. DaveBaldwin

    108,635

    Master

    2,000 points yesterday

    Profile
    Rank: Genius
  4. ChrisStanyon

    101,266

    Master

    0 points yesterday

    Profile
    Rank: Sage
  5. tommyBoy

    65,616

    Master

    0 points yesterday

    Profile
    Rank: Genius
  6. kozaiwaniec

    57,116

    Master

    2,000 points yesterday

    Profile
    Rank: Guru
  7. nap0leon

    53,757

    Master

    0 points yesterday

    Profile
    Rank: Sage
  8. xmediaman

    50,100

    Master

    0 points yesterday

    Profile
    Rank: Guru
  9. jason1178

    49,680

    0 points yesterday

    Profile
    Rank: Genius
  10. SSupreme

    43,018

    0 points yesterday

    Profile
    Rank: Wizard
  11. Kravimir

    42,150

    0 points yesterday

    Profile
    Rank: Genius
  12. s8web

    40,064

    0 points yesterday

    Profile
    Rank: Sage
  13. therealteune

    35,300

    0 points yesterday

    Profile
    Rank: Wizard
  14. webmatrixpune

    30,818

    0 points yesterday

    Profile
    Rank: Guru
  15. HagayMandel

    27,880

    0 points yesterday

    Profile
    Rank: Guru
  16. zappafan2k2

    23,368

    0 points yesterday

    Profile
    Rank: Guru
  17. leakim971

    22,966

    0 points yesterday

    Profile
    Rank: Genius
  18. HainKurt

    20,000

    0 points yesterday

    Profile
    Rank: Genius
  19. jagadishdulal

    19,668

    0 points yesterday

    Profile
    Rank: Guru
  20. Proculopsis

    19,350

    0 points yesterday

    Profile
    Rank: Sage
  21. mplungjan

    19,232

    0 points yesterday

    Profile
    Rank: Savant
  22. basicinstinct

    19,026

    0 points yesterday

    Profile
    Rank: Genius
  23. anuradhay

    19,006

    0 points yesterday

    Profile
    Rank: Guru
  24. jtwcs

    18,808

    0 points yesterday

    Profile
    Rank: Master
  25. gurvinder372

    18,057

    0 points yesterday

    Profile
    Rank: Genius

Hall Of Fame