Cascading Style Sheets (CSS) provide a higher level of abstraction over the presentation of web pages. The definitive guide to CSS is at the www.w3.org.
- Reasons to use CSS
- CSS separates your content from presentation.
- With CSS an entire web site can change look by changing one file (csszengarden).
- Using CSS can lower your bandwidth costs.
- Your HTML is easier to read and understand making maintenance cheaper.
- People with disabilities can access your pages easier.
- Organizations can share the same style across web sites.
- Menus can be created without javascript.
Old Style:
<p><font size="7" face="Georgia, Arial" color="red">Error: I'm sorry Dave, I'm afraid I can't do that.</font></p>
New Style with CSS
<p class="error" >Error: I'm sorry Dave, I'm afraid I can't do that.</p>
We put the styling in a separate file that can be used in many places:
.error { font-size: 12pt; font-family: Georgia, arial, sans-serif; color: red; }
- Rules
- General format of CSS:
A CSS is composed of a series of rules. A rule is a "type selector" followed by curly braces enclosing one or more "declarations". A declaration is composed of a property, a colon, a value, and a semi-colon (the last one before the '}' is optional). White space is not significant between tokens.
selector { propertyName1: propertyValue1; propertyName2: propertyValue2; ... }
- Selectors
- Element Type Selector
Example of specifying attributes for a single element type
h2 { font-size: 16pt; font-family: arial,helvetica,"sans serif"; color: black; font-weight: normal; }
Note: property values with more than one word should be placed in quotes as above with "sans serif".
- Universal Selector
This effects all elements
* { color: green; }
- Class Selector
The "." is the class selector character. This affects all elements with a particular "class". ("Bundle" would have been a better name. A class is a predefined bundle of css rules.)Define a class by giving it a name (always preceded by a period) and adding the standard style definition of properties and values inside curly brackets:
in the document:.periwinkle { color: #6699ff; }
becomes:<p class="periwinkle">This is bold, periwinkle text.</p>
This is bold, periwinkle text.
You can specify that a style will apply only to a particular element type. For example, only paragraphs with the class "periwinkle" will be affected by the following:
p.periwinkle { color: #6699ff; }
Elements may have more than one class, separated by spaces
If the style sheet contains:And the text is:.periwinkle { color: #6699ff; } .tiny { font-size: 70%; }
The result will be:<p class="periwinkle tiny">This is tiny, periwinkle text.</p>
This is tiny, periwinkle text.
- id Selector
This effects the single element with this "ID". In the style sheet, ID selectors are prefaced with a '#'.
in the document:#big { font-size: 250%; }
becomes:<p id="big">This is BIG text.</p>
This is BIG text.
- Pseudo Element Selectors
This are used to style particular parts of an element. Pseudo Elements are prefaced with "::" to distinguish them from Pseudo Class which start with a single ":". Common examples are: ::first-line, ::first-letter, ::selection, ::before and ::after. (The "::" is not supported in all browsers, although some take a single colon nicely. IE is still having issues with some of these.)
This will render correctly on Firefox and a little awkward in IE6:p.test:first-letter { font-size: 200%; float: left; font-style: italic;} ... <p class="test" style="border: solid thin;"> Once upon a time there were four little rabbits, and their names were Flopsy, Mopsy, Cotton-tail and Peter.</p>
Once upon a time there were four little rabbits, and their names were Flopsy, Mopsy, Cotton-tail and Peter.
- Dynamic Pseudo Class Selectors
For elements that change over time or conditions. CSS2 defines hover, active, focus, link, and visited,lang(). Example: if the style sheet contains
a.test:hover { background-color: red; }
and the html looks like this:
<a href="#" class="test">Example link with red background.</a>.
This will render with a red background when the cursor hovers over it:
Example link with red background..To specify a color for visited links,
a:visited { color: #999; }
- Structural Pseudo Class Selectors
These select elements based on their position in the structure of the document. Examples: :root, :first-child, :last-child, :empty. This is defined in CSS3 and is supported by most browsers, but not IE.
- Parent Child Selectors
To specify that when an element is a direct descendant to another to use a particular style
li>p { font-style: italic; }
then paragraphs appearing inside of list items will be in italics only if they are direct descendent's
- Descendant Selector
You can assign properties to elements that descend from another element. For example, all "em" tags descended from a "p" tag will be 120% than normal.
p em { font-size: 120%; }
"I believe I have peace in our time."
- Adjacent Selectors
Specify a rule when two elements are next to each other. This applies to the element on the right.
li+p { font-style: italic; }
The paragraph adjacent to the "li" element will be in italics.
- Attribute Selectors
Applies rules to elements with particular attributes and values
input[type="text"] { font-style: bold; }
- font-variant can be used to give special effects like small caps
<H2 style="font-variant: small-caps">
Example:Napoleon defeated at Waterloo!
- More than one selector can be on the same line separated by commas
In this example all h1, h2, and h3 elements are declared to be red.
h1, h2, h3 { color: red; }
- To specify that when an element is contained by another to use a particular style, do not use commas,
Example: li p { font-style: italic; }
then paragraphs appearing inside of list items will be in italics
- Element Type Selector
- General format of CSS:
- Style Sheets
Style Sheets are files typically with a ".css" extension containing rules. The four and a half ways of linking pages to Style Sheets:
- External
Use an external file and specify it's location with the "link" command in the head section (preferred method). More than one can be included.
<head> <title>KnowledgeBase/Web/CSS - Examples of CSS</title> <link href="https://www.fincher.org/mystyle.css" rel="stylesheet" type="text/css" /> <link href="https://www.fincher.org/style/css.css" rel="stylesheet" type="text/css" /> </head> <body> ...
The file "mystyle.css" would contain something like,
h1 {border-width: 1; border: solid; text-align: center} h3.green { font-family: Arial; font-style: italic; color: green } span.html { color:#ff0000 }
- Embedded
<head> <style type="text/css"> h3 { font-family: Arial; font-style: italic; color: green } h1 {border-width: 1; border: solid; text-align: center} h3.green { font-family: Arial; font-style: italic; color: green } span.html { color:#ff0000 } </style> </head>
- In line
CSS commands can be used in a tag declaration:
<h2 style="color:blue">My Subtitle<h2>
- Import with '@'
In the heading section put something like,
<style type="text/css"> @import url(https://www.fincher.org/mystyle.css); </style>
- Nesting Style Sheets
A style sheet can import another style sheet. For example in my "Beach.css" style sheet I have the following:
@import url("https://www.fincher.org/style/Menus.css"); @import url("https://www.fincher.org/style/Basic.css"); @import url("https://www.fincher.org/style/Position.css"); body { background: url("https://www.fincher.org/images/Sand-1280.jpg"); background-attachment: fixed; background-repeat: repeat; background-position: center; }
Inside "Plain.css" we reuse the simple style sheets and add specific colors:
@import url("https://www.fincher.org/style/Menus.css"); @import url("https://www.fincher.org/style/Basic.css"); @import url("https://www.fincher.org/style/Position.css"); body { background-color: transparent; color: black; text-align: center; background-attachment: fixed; background-repeat: repeat; background-position: center; }
Note: comments in css are put inside "/*" and "*/" strings.
- External
- Length Units
CSS provides many units. Relative units are usually preferred since they are more flexible.
- Relative Units
- em (ems, the height of the element's font)
- ex (x-height, the height of the letter "x")
- px (pixels, relative to the canvas resolution)
- Absolute Units
- in (inches; 1in=2.54cm)
- cm (centimeters; 1cm=10mm)
- mm (millimeters)
- pt (points; 1pt=1/72in)
- pc (picas; 1pc=12pt)
- Percentage
A percentage value is prefaced with an optional + or -, followed by numbers, followed by %. Example: .tiny { font-size: 70%; }
- Relative Units
- Examples of using selectors
- Changing the look of an element.
To change all instances of an element:
Then the following HTML code<head> <style type="text/css"> h3 { font-family: Arial; font-style: italic; color: green } </style> </head>
becomes<h3> This is a green Arial header3 </h3>
This is a green Arial header3
- span is good to use for text inside a paragraph. example
Inside the header section put something like,
<style type="text/css"> span.javascript { color:#00aa00 } span.lang { font-size: 18pt; color:#0000aa; } </style>
And then in your text enter,
Then your text will look like this:My favorite language is <span class="lang">Ruby</span>!
My favorite language is Ruby! - To use style sheets inside a table, you can use TH and TD
<style type="text/css"> body, th, td {font-family: Comic Sans MS,Helvetica, Verdana, sans-serif;font-size: 10pt;} </style>
- Text Decoration
the "text-decoration" property modifies the text.
Possible values: none underline overline line-through blink
.title { text-decoration: underline; }
becomes:<div class='title'>State of Fear</div>
State of Fear - Text Transformations
the "text-transform" property can format text. Common values are capitalize, uppercase, and lowercase. Example:
<p style="text-transform: uppercase;">This is all uppercase.</p>
This becomes:
This is all uppercase.
- The "white-space" property
The line breaks and white space can be preserved.
<p style="white-space: pre; border: solid 1px black;"> drip, drip, drip, drip the rain would not stop. </p>
This becomes:
drip, drip, drip, drip the rain would not stop.
- line-height
To control the spacing between lines use line-height.
<p style="width: 20em; line-height: 0.75em;" class="boxed"> The sky above the port was the color of television, tuned to a dead channel. (line-height: 0.75em) </p>
The sky above the port was the color of television, tuned to a dead channel. (line-height: 0.75em)
The sky above the port was the color of television, tuned to a dead channel. (line-height: 2em)
- The cursor can be set to a new shape by something like this:
<span class="bordered" style="cursor: wait;">wait</span>
Move your cursor over the following:
crosshair pointer wait help move text - Shorthand Properties
Many properties are assigned over and over. To minimize wear and tear on our fingers the W3 allows many "shorthand" properties.
instead of typing:You can enter,padding-top: 3px; padding-right: 2px; padding-bottom: 1px; padding-left: 0px;
padding: 3px 2px 1px 0px;
Note: Most shorthand properties follow the same Top,Right,Bottom,Left format, which is TeRrBiLe.
- Vendor-specific extensions
Keywords and property names, beginning with '-' or '_' are for vendor-specific extensions. The vendor's code name immediately follows the '-' or '_'.
-moz-border-radius: 3px;
- Precedence
The wonderful thing about Cascading Style Sheets is that word "Cascading". You can set a general style for your web site and only override that style when you want an exception. Generally, the last most specific style wins. This can be overridden with the "!important" rule modifier.
p { color: red !important; }
Now, even though a more specific rule might apply to a paragraph, this "important" one will override it. In case of multiple "!important"s, the last one wins.
- To set a background image:
background-image:url(https://www.fincher.org/images/gray_rock.gif);
The rash of background properties (color,image,repeat,position, attachment) can zipped into the "background" shorthand property:
background: url(https://www.fincher.org/images/BlueMarble.jpg); transparent no-repeat fixed top left;
- Changing the look of an element.
- Positioning
- Aligning blocks with "margin-right: auto" and "margin-left: auto"
This paragraph is margin-right: auto.
This paragraph is margin-left: auto.
- Using the overflow property
"overflow" specifies how to display content that does not fit in the box.
This paragraph uses "overflow: auto" with a fixed width and height and a thin solid black border.
This paragraph uses "overflow: visible" with a fixed width and height and a thin solid black border.
- "float" allows content to move to one side and be wrapped by other content. Floated elements are treated as block elements. Values for float are left, right, none, or inherit.
I'm floated left.
I am just regular old text, not floated at all.
- Block vs. Inline elements
The following table details some differences between Block and Inline elements.
Attributes Block Inline Accept attributes like width and height Yes No. Only as big as its contents Width Expands horizontally to take up the whole line Expands only enough to contain its contents. Several inline elements can be on the same line comfortably, like bosons. May Contain Blocks and Inline elements Only other inline elements Examples <p>, <li>, <h1>, <form> and <div> <span> and <em> Elements can be changed from inline to block by using the "display" property.
spanspanspanspan with display: block;spanspanspanspanAs spans can be turned into block elements, block elements can be displayed as inline:
<p style="display: inline" class="boxed"> I'm an inline paragraph</p> <p style="display: inline" class="boxed"> I'm an inline paragraph</p>
I'm an inline paragraph
I'm an inline paragraph
- To create layers
Example shows how to use z-index to make one div float on top of another
<div style="background: transparent; height: 40px; width: 250px; position: relative; font-size: 40px; z-index: 1;">Happy</div> <div style="background: transparent; height: 80px; width: 350px; position: relative; top:-50px; left:30px; color:red; font-size:80px; z-index:2">Birthday!</div>
This produces:
HappyBirthday! - Using Css with tables
table#joketable { background-color:#ccccff; width: 100%; } table#joketable td.author { padding: 5px; width: 25%; } table#joketable td.ratingbox { padding: 0.4em 0 0 0.4em; width: 25%; }
For a table like this:
Joke Rate It! (25% width) Author (25% width) What did the bowling pin say to the bowling ball? "Please spare me!" 6 jeremy from New York - To center tables in a page
table { margin: auto; }
- Special handling for printing
CSS allows rules that apply only when printing. For example, the following prevents the menus and ads from this site from printing, since they are meaningless on paper.
@media print { #menus, #adsRight, #adsBottom { display: none; } }
- How to center tables
Since 'align="center" is frowned upon (and deprecated) use "margin: auto" to center tables.
table {margin: auto; }
- Problems with CSS
- No variables, no inheritance
- Browser Support
- Browser Support (See acid2 test).
- Tools and Tip Sheets
-
An essential tool for doing CSS is the "Web Developer" application in Firefox or Chrome. In most browsers you can bring up the developer tools with F12
Chrome has the best css/html inspector I think. On the mac enter Command-Option-i to bring up the window.
- A good cheat sheet by Robert Mening is here..
-
- The Really Big Idea behind style sheets
All the HTML tags names are not magic, they just have a corresponding css style associated with them. You could write complete, valid, wonderful web pages using a whole new set of tags with an associated style sheet. Instead of using <p> you could use "my paragraph", <mp> and instead of <b> you could use <mb>, and <mem> instead of <em> if you set the style of these to something like:
Then a sample text consisting ofmp { display: block; text-indent: 2em; line-height: 90%;} mb { font-weight: 800; } mem { font-style: italic; }
<mp> Twas brillig, and the <mem>slithy</mem> toves Did gyre and gimble in the wabe: All mimsy were the <mb>borogoves,</mb> And the mome raths outgrabe. </mp> <mp> "Beware the Jabberwock, my son! The jaws that bite, the claws that catch! Beware the Jubjub bird, and shun The frumious Bandersnatch!" </mp>
would look like this:
Twas brillig, and the slithy toves Did gyre and gimble in the wabe: All mimsy were theborogoves, And the mome raths outgrabe."Beware the Jabberwock, my son! The jaws that bite, the claws that catch! Beware the Jubjub bird, and shun The frumious Bandersnatch!" So, the really big idea is that HTML tags are sort of a presupplied started kit of tags, but just an example of using CSS. Although creating your own tags is now discouraged.
- Aligning blocks with "margin-right: auto" and "margin-left: auto"
- Positioning
CSS provides four ways to position elements on a page and not merely to style them.
- static
The default positioning for css is called "static". Elements are stacked on top of each other in a normal flow from first to last.
#outer, #one ,#two, #three, #four, #five {position: static;} #outer { background-color: #aaa; padding: 2em; } #one { background-color: #aaf; } #two { background-color: #afa; margin-left: 15em;} #three { background-color: #aff; } #four { background-color: #faa; } #five { background-color: #ffa; }
HTML code like the following:
<div id="outer"> <!-- outer --> outer div <div id="one"> div one</div> <div id="two"> div two</div> <div id="three"> div three</div> <div id="four"> div four</div> <div id="five"> div five</div> </div> <!-- outer -->
looks like this:
outer divdiv onediv twodiv threediv fourdiv five - relative
position is based relative to its parent.
- absolute
"absolute" positions elements within their parent at particular locations.
You can see what it looks like here.looks like this:
- fixed
position is based relative to the screen.
- static
- Some of my favorite Online References for CSS:
- Introduction to cascading style sheets css/
- Layout techniques at https://www.glish.com/css/
- css1 properties
- Cascading Style Sheets
- w3.org's css validator
- w3.org's Cascading Style Sheets