<

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

Getting the Most out of CSS

Published on
18,508 Points
6,808 Views
22 Endorsements
Last Modified:
Awarded
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">

Open 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;
}

Open 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;
}

Open 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>

Open 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;
}

Open 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;
}

Open 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;
}

Open 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;
}

Open in new window

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

Open in new window

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

Open 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;
}

Open 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;
}

Open 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>

Open 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>

Open in new window

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

Open 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;
}

Open 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>

Open 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;
}

Open 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;
}

Open 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>

Open 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;
}

Open 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;
}

Open in new window

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

Open 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;
}

Open 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;
}

Open 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/
22
Comment
Author:MageWind
  • 4
  • 2
  • 2
  • +1
9 Comments
LVL 16

Expert Comment

by:Geoff Kenyon
MageWind,

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

Author Comment

by:MageWind
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.
0
LVL 48

Expert Comment

by:aikimark
Questions about precedence:
* Does Inheritance trump Proximity?
* Does Proximity trump Specificity?
* Does Specificity trump The Latter Wins?
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

LVL 16

Expert Comment

by:Geoff Kenyon
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.
0
LVL 3

Author Comment

by:MageWind
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>

Open in new window

0
LVL 17

Expert Comment

by:mreuring
@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 ;)
0
LVL 3

Author Comment

by:MageWind
@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? =)
0
LVL 3

Author Comment

by:MageWind
If you liked the article, please say so at the top-right of the article =D
0
LVL 17

Expert Comment

by:mreuring
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 :)
0

Featured Post

Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Join & Write a Comment

In this tutorial viewers will learn how to define a gradient in CSS. Create a new HTML document with an internal stylesheet.: Create a div in CSS and name it Gradient. Define the background as "linear-gradient(to right, #ee3668, black)". Ensure you …
In this tutorial viewers will learn how add a scalable full-width header using CSS3. Create a new HTML document with an internal stylesheet. Set a tiled background.:  Create a new div and name it Header. Position it with position:absolute at the top…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month