- Contents
- What is CSS?
- Inheritance
- Selectors
- Demonstration
- Specificity
- CSS Rule Placement
- Default Style Sheet
- CSS Reset
- Last Style Definition Wins
- The Cascade
- CSS Rules
- Selectors
- IDs and Classes
- Pseudo Classes
- Not Example
- Pseudo Elements
CSS, or cascading style sheets, describe the presentation of web pages, including colors, layout, and fonts. It does this through properties that style the HTML tags.
Think form and content. CSS is the form, HTML is the content.
CSS is separate from the content, allowing it to adapt the presentation to different types of devices, such as large screens, small screens, or printers.
The separation of HTML from CSS makes it easier to maintain sites, share style sheets across pages, and tailor pages to different environments.
CSS is deceptively easy to apply when it is done inline. That means you write the code right into the HTMl tags using the style attribute. You write these locally applied rules like this: style="inline CSS rules go here"
. The addition of the code style="color: red"
to the paragraph tag <p >
looks like <p style="color: red">
, and colors the following paragraph red.
Changes are seen as soon as you update the browser. This immediacy and the simplicity of the syntax makes CSS appear easy, which it is when there is no cascade or style sheets to worry about.
It is possible to write all of your presentation in the tags themselves, but you would find that to be highly inefficient. It is generally frowned upon to write CSS locally, as that defeats the purpose.
What is CSS?
CSS gets its power from inheritance, the style sheets and the cascade. It is called CSS, or cascading style sheets. With that power comes the responsibility of keeping track of all the sectors that target the html element, and that makes CSS difficult.
Not all properties are inheritable, but those that are can be set in the html or body tag, and every child tag will inherit these properties.
The cascade describes how the CSS rules in the style sheet are globally applied. The style sheet is a list of rules prefaced by one or more selectors. These rules are placed in the header of the page or are in an external style sheet, in which case, a link to that style sheet is placed in the header of the page.
Selectors provide the link between the rules in the style sheet and the HTML elements that receive the rule. The browser parses the document, figures out every element in the document tree, heals any errors it may find, and tracks all of the selectors used by the style sheet to target the different tags so that it can assign the rules of properties and their values to each element, so that the page ends up looking the way it does.
</div>
Inheritance
Every element is a child of the html
element. If you target the html
, or the body
element, many properties will be inherited, but not all.
For example, a child element inherits the font property of its parent, but it will not inherit the background property. Other properties that are automatically inherited. Some of these properties are: color, font (and related properties), letter-spacing, line-height, list-style (and related properties), text-align, text-indent, text-transform, visibility, white-space and word-spacing.
Properties not automatically inherited are: background (and related properties), border (and related properties), display, float and clear, height and width, margin (and related properties), min- and max-height and -width, outline, overflow, padding (and related properties), position (and related properties), text-decoration, vertical-align, z-index. There are more, but this gives you an idea.
Inheritance prevents certain properties from having to be declared over and over again in a style sheet, allowing the developers to write less CSS and the users to view faster-loading pages.
Inheritance plays a large roll in CSS, but it’s not overtly visible. Be aware that it’s constantly determining what the elements on the page look like. In the cascade, inherited properties lose out to any properties provided by a selector.
CSS Selectors
Central to this process is the selectors that connect the CSS properties to the element when the properties are no longer written in the element itself.
There are many kinds of selectors, and W3C has a whole list of them, I have a reduced set of them below. It is best to keep things simple, and start with the type selector.
You can select all paragraphs in a document by using the type selector, like this: p {css: rule;}
.
An interactive demonstration can be of great help in conveying the information. What follows is the first of many such interactive demos.
Interactive CSS Selectors Demo
The following demonstration selects all of the text contained by <p>
in this document. You can change the font, the type color and the type size (or anything else if you write in the rule).
Words inside of /* */ are comments there to help you come up with values that match the properties, for example, /*green, #123456*/
are suggestions to replace black with green in color: black
.
Without all of the suggestions, all that is being specified is p { font-family: Georgia, serif; color: black; font-size: 1em;}
Your changes could render the document unreadable. To reset the document, refresh the page. The selector <p>
selects all paragraph elements.
If you find something you like (this concerns the other demos), then copy the definitions and use them in your document.
CSS Code View
If you colored the text green
, you will notice that the paragraph above that was originally colored red is still colored red. Why did the color not change? The same is true of the font-family
.
We will explore this in much greater detail, but know for now that there is a cascade determining which rule wins out over all the other rules that are targeting the element.
You can overpower the cascade order by using !important
, which is inserted right after the value and before the semicolon. Try inserting !important
in the demo, and you will see that the global CSS rules now override the local inline rules in the cascade.
The problem with using !important
is that it quickly destroys the cascade, and it will make your CSS unusable, so it is not recommended unless you have no other options.
Specificity and Grouping Selectors
It’s not always desirable to select all the paragraphs in the document. We usually want to select very specific paragraphs, or elements, in the document. This paragraph or that paragraph, but not all of them. This is achieved by nesting selectors.
Selectors can be nested to achieve greater specificity. In the following demonstration, each line is targeted individually by nesting the selectors. That means using a space “
” between the selectors to specifically select the child element inside of the parent element:
Selectors can also be grouped to share the same rules. That means using a comma “ ,
” between the selectors to include all of the selectors to which the rule will be applied. This is the case with the last two selector in the demonstration:
CSS Code View
Header in div
Paragraph in div
- Item 1 of list in div
- Item 2 of list in div
The blue div has the 120% applied twice, and is larger than all other text in this demonstration. Another example of the cascade at work. Play around with the demo to see how specificity is able to narrow the targeted section to exactly the element that you want to style.
The HTML code for this example is:
<div id="example0"> <h2>Header in <span>div</span></h2> <p>Paragraph in <span>div</span> <ol> <li>Item 1 of list in <span>div</span> <li>Item 2 of list in <span>div</span> </ol>
CSS Rule Placement
There are three places where you can put your style definitions.
Inline Style definitions
CSS styles can be written in the tag itself, called inline styles, in the head of the document, called embedded styles and in an external style sheet:
You can write the style directly in the tag itself as we have been doing:
<p style="color: red">
Embedded Style definitions
The next easiest place to put the CSS is in the <head>
of the document between <style>
and </style>
tags. Using a p
selector it’s possible to target all the paragraphs in the document with the embedded style.
<style type="text/css"> p { color: red} </style>
The rules are now enclosed in brackets, and in front of the bracket is a selector that targets which element will be affected by these rules. The rule has been severed from the element itself, which allows it to be applied to many elements, but it increases the complexity, as different selectors with conflicting style rules can target the same element. Who will win out to style the element? That is the question.
This is were it can get difficult, as several rules can target the same element, and when that happens, the browser has to select which rule wins out in what’s called the cascade.
Embedding the styles is more efficient than writing them inline in each paragraph element, it’s still not ideal, since it only targets the tags in the page, and websites almost always consists of multiple pages.
External Style Sheets
The most efficient place for styles is in an external style sheet. The external style sheet is a simple text file with nothing but CSS rules on it styled. They can be written in any way, as spaces, returns and tabs are ignored by the browser. Start out by separating all of the properties in their own line, as in the following example, so that they are easy to read:
p { color: red; background: white; width: 400px; padding: 20px; border: 2px solid green; margin: 20px auto; }
Just so you know, it is also possible to write the declarations in one line:
p {color: red; background: white; width: 400px; padding: 20px; border: 2px solid green; margin: 20px auto;}
There is no difference, as all the white space is collapsed.
The file is saved with a .css
extension, often in its own folder called CSS, in case there are more than one external or imported style sheets. Each HTML page in the site then refers to that style sheet by linking to it. To do that you need to include the following code in the header of each document:
<link rel="stylesheet" href="CSS/styles.css" media="all">
You can copy this into your pages, though I have already included it in the HTML5 template.
It’s possible to link to or import several style sheets and some think it’s a good organizing principle to break the styles into several style sheets like the CSS reset, typography, navigation, layout and alternate styles for IE 6.5, 7 and 8.
The downside to all this organization is that each stylesheet requires a server request, that is, your browser has to ask the server for one more file to complete the page, and the lag time involved in asking the server for each style sheet can take more time than the actual loading of the stylesheet itself. Because of this, a more common approach is to put all the styles into a single style sheet.
Browser’s Default Style Sheet
Even if you do not write any CSS, the HTML has formatting applied, so that an <h1>
tag looks different from an <h2>
or a <p>
tag. Where do these styles come from?
Every browser has a default style sheet, called the user agent style sheet, like this one from Safari, that formats the markup.
User Agent styles
are the default style sheet the browser uses, which are modifiable by an end user. Author styles are the ones that you create when you design the page. There are also user styles, which is style information specified by the user apart from the default style sheet. We will not concern ourselves with that.If you look at Safari’s default style sheet, you will see that it determines how the p
element is to be displayed:
p { display: block; -webkit-margin-before: 1__qem; -webkit-margin-after: 1__qem; -webkit-margin-start: 0; -webkit-margin-end: 0; }
When you see a paragraph in an HTML document that has not yet been styled, it looks as specified by the browser style sheet. If you start styling the elements with your own styles in an author style sheet, they will be built on top of the styles specified in the user agent style sheet. That may lead to problems when the page is looked at in a different browser.
Resetting the Browser Default Style Sheet
To counteract the possibility that your author styles change with different browsers, you need to neutralize the default user agent style sheet the browser uses.
To counter this we implement a CSS reset. The CSS reset was initiated by Eric Meyer, and he recently released a second version. Take the following code and place it at the beginning of your style sheet, and it will neutralize the default styles of the browser style sheet.
/* Begin CSS Reset */ /* http://meyerweb.com/eric/tools/css/reset/ v2.0 | 20110126 License: none (public domain) */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } /* HTML5 display-role reset for older browsers */ article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } table { border-collapse: collapse; border-spacing: 0; } /* End CSS Reset */
Last Style Definition Wins
There is a pattern here. The styles in the author style sheet override the styles in the user agent style sheet. In the order in which CSS rules are compiled, subsequent declarations override previous ones.
If you repeat the same property twice, the second one will style the element. {color: green; color: red}
The type will be colored red, and not green.
This is also true of the three places where you can place the rules. If the same rule is found in the user agent style sheet, the author’s style sheet and any other imported external style sheets, the embedded or internal style sheet and repeated once again inline, that is, in the element itself, guess which rule wins out?
The inline rule wins out. The rule of thumb is that the closer to the style definition is to the element being styled, the more likely it is to triumph over all the other rules, and style the element. The insight that we are left with is that the order in which the browser concatenates the various style sheets is as given above, with the default style sheet first, then external style sheets, then the internal style sheet and finally it arrives at the elements themselves.
That the last style definition wins is part of the cascade:
The Cascade
CSS stands for cascading style sheets. The cascade describes the way selectors target their elements.
CSS rules can be written in a number of places. It is, therefore, possible that an element can be targeted by several rules — from inline rules to embedded rules to external rules, to user stylesheets. When there are several rules targeting the same property with different values, only one of these rules will win out. Figuring out which rule ends up styling the element is very important, and that is what the cascade is all about.
For example, <span style="color: red">red</span>
this text’s inherited default color of black
is overridden by the inline style that colors the type red
. That tells you that the inline style trumps the inherited style.
The browser needs to figure out which rule to use when there are multiple conflicting values for a property. The cascade refers to the selection process in which these styles are evaluated so that only one value ends up styling the element.
Generally speaking, the closer a style definition is to the tag, the more likely it wins out. The inline style wins out over the embedded style, the embedded style trumps a linked or imported style sheet which in turn wins over the browser’s default style sheet, and they all trump inherited styles.
The cascade takes the selector’s specificity into its calculation. One selector will trump all other selectors. A formula determines the cascade. It prioritizes ids over classes, for example. Classes win out over structural tags, and structural tags trump typed tags.
You can pull out the big gun and place !important
after a rule if you absolutely want it to be the case no matter what.
Be very judicious in your use of classes, ids and especially !important, as you can easily make a document unmanageable. The rule of thumb is to use as low a cascade value as possible to select an element.
The Elements of a CSS Rule
CSS has a simple syntax and uses a number of English keywords to specify the names of various style properties. A style sheet consists of a list of rules. Each rule or rule-set consists of one or more selectors, and a declaration block. A declaration-block consists of a list of declarations in braces. Each declaration itself consists of a property, a colon (:), and a value. If there are multiple declarations in a block, a semi-colon (;) must be inserted to separate each declaration.
The CSS rule describes what an element should look like, and when combined with a selector to select the element, you have a complete CSS statement.
The CSS Rule
The CSS rule contains both the selectors and the declarations.
Example: h1 {font-size:1.5em; font-weight: 700; color: #333; }
The Declaration
The declaration is a property-value pair, and is part of the rule that describes how the selector will style the element. When the style sheet is embedded in the document, convention is to follow each declaration inline:
Example: h1 { font-size:1.5em; font-weight: 700; color: #333;}
While in an external style sheet, convention is the put each delectation on a new line with a tab in front:
Example: h1{
font-size:1.5em;
font-weight: 700;
color: #333;
}
The Declaration Box
These are all the declarations that determines how the selector will style the element. it’s always bookended by { }
(curly braces).
Example: h1 { font-size:1.5em; font-weight: 700; color: #333;}
Properties
A property describes an aspect of an elements’s presentation, such as color, font-size or border-width. The property is always followed by a value, and the two are always separated by a :
(colon). There are a lot of properties, so it’s best to have a place where you can look them up, though frequent usage will acquaint you with the ones you need.
Example: h1 {color: #356590; padding: 3px 16px;}
Values
A value describes a specific appearance, such as a specific width, the name of a color, or some set value, such as for text-decoration: none; which removes the underline from text, often used to remove the underline that the browser’s default stylesheet gives a link. The value commences the declaration statement, and you signify that to the computer by using a ;
(semicolon). While it’s not necessary to tell the browser that there are no more declarations in the declaration box, it’s a good practice to close the last declaration as well.
Example: h1 {color:#356590; padding: 3px 16px;}
Selectors
Selectors are patterns that match the elements of a document that will then have the declarations applied to them.
There are four categories of selectors: ID rules, Class rules, Tag rules and Universal rules. IDs carry more weight than classes, which carry more weight than Tag rules, which carry more weight than the universal rules.
The most immediately understandable selector is the type selector, in which p
selects the paragraph element: <p>
.
example of simple type selector: p { }
There are many more precise ways of selecting just the element you want, as there will probably be a lot of p
elements in the document, and selecting the right one takes more precision. As a matter of fact, there are 45 different kinds of selectors, to be exact, but that is more than we need to comprehend here.
Structural Selectors and Pseudo Classes
Then there are structural and pseudo class selectors, which take advantage of the natural structural properties of the nested markup to select elements, like the #example ol li:first-child { }
, which selects the first list item in the ordered list. You can see that this over-rides the type selector, even hough the type selector comes later on in the code.
Id’s and Classes
If none of these methods work and you still cannot select an element, you can always create a class or an id to link up a CSS rule with elements that are the given the class or id properties with the same name.
CSS Selectors
Selectors are patterns that match the elements of a document that will then have the declarations applied to them. The easiest selector to understand is the type selector, in which p
selects the paragraph element: <p>
.
example of simple type selector: p { }
There are six different types of selectors, type , universal , attribute , class , ID and pseudo class.
The type selector selects the element by the tag itself:
Type: p { }
The universal selector selects all elements:
Universal: * { }
Example of an attribute selector that selects all image tags with an attribute of “alt”:
Attribute: img[alt] { }
Another example of an attribute selector that selects all links to pdf files.
Attribute: a[href$=”.pdf”] {color: #45a2f4;}
Example of a class selector that selects any element with a class=”example”:
Class: .example { }
Example of a ID selector that selects any element with an id=”container”:
ID: #container { }
Example of a pseudo selector that selects any link and creates a hover class:
Pseudo Class: a:hover { }
To make matters more precise, selectors can be combined by using a space
, a greater than sign >
for limiting that combination to a child of the selected parent, a plus sign +
for selecting directly adjacent elements and the tilde ~
for selecting indirectly adjacent selectors.
Space: article p { }
selects all <p> elements in <article>.
Greater Than: article>p { }
selects only the <p> elements that are children of the <article>.
Adjacent: article+p { }
selects only the <p> elements adjacent to the <article>.
Tilde: article~p { }
selects all indirectly adjacent <p> elements to the <article>.
When several selectors share the same declarations, they can be grouped into a comma-separated ,
list:
example: h1, p, img, nav { }
The last selectors are a number of useful structural pseudo classes. What a mouthful, right? They allow the first, last or alternate lines to be selected, for when you want to alternate the color in a set of links, for example:
First Child: tr:first-child { }
Last Child: tr:last-child { }
Nth Child: p:nth-child(2) { }
Ids and Classes
HTML uses the Id and Class attributes for general naming of the elements. This is used by Javascript as well as CSS to select these elements.
An id is to be assigned only once per page, while classes can be assigned multiple times per page. That difference gives ids more weight than classes when it comes to the CSS cascade.
Ids and Classes so obviously connect the rule with the element that they were over-used in the past when other selectors could have worked just as well. If it were a screaming contest, it was an outright cacophony. That particular affliction, along with the overuse of the generic div element, is called divitis and classitis. It is best to be as quiet as possible, and not jump to using classes and ids unless necessary.
In the markup the id uses a hash mark #
before the name in the style sheet and the HTML code looks like <div id="this">
, while the class uses a period .
before the name in the style sheet and the HTML code looks like <div class="that">
.
Pseudo Classes
Pseudo classes create a class of an element that already exists, but where there is no predetermined class. You can select a link, the anchor tag, but there is no class to select the hover state of that link. This pseudo-class selector creates a pseudo class that can be styled as the link’s hover state. Many of these pseudo classes are structural, meaning that they use information that lies in the document tree to select different elements.
here is a list of the pseudo classes:
- :nth-child(N)
- matches elements on the basis of their positions within a parent element’s list of child elements (N here stands for the number of the element, but it can also support odd and even, as in li:nth-child(odd))
- :nth-last-child(N)
- matches elements on the basis of their positions within a parent element’s list of child elements
- :nth-of-type(N)
- matches elements on the basis of their positions within a parent element’s list of child elements of the same type
- :nth-last-of-type(N)
- matches elements on the basis of their positions within a parent element’s list of child elements of the same type
- :last-child
- matches an element that’s the last child element of its parent element
- :first-of-type
- matches the first child element of the specified element type
- :last-of-type
- matches the last child element of the specified element type
- :only-child
- matches an element if it’s the only child element of its parent
- :only-of-type
- matches an element that’s the only child element of its type
- :empty
- matches elements that have no children
- :target
- matches an element that’s the target of a fragment identifier in the document’s URI
- :checked Pseudo-class
- matches elements like checkboxes or radio buttons that are checked
- :not(S)
- matches elements that aren’t matched by the specified selector
Pseudo Classes: not
A collapsable guide to the layout modes. All of the work is being done by the last CSS rule using the pseudo class not, as in not target or hover li:not(:target):not(:hover)
.
CSS Code View
Live Demo
Pseudo Elements
CSS can create markup where there is none. These are called Pseudo Elements, and you can style them as if they existed.
For Example, if you wanted to style the first letter of a paragraph, you can target it even though there is no markup. There are four pseudo elements all together: first letter, first line, before and after. All of them are written using another selector, two colons ::
and the pseudo element, as in p::first-letter {}
(The double colon is new, so a single colon is also accepted).