CSS

Cascading Style Sheets provide the language used for describing the presentation aspects of an HTML document, i.e. the look and formatting.

 

  • Developed by World Wide Web Consortium
  • Initial release 17 December 1996
  • CSS2 released 12 May 1998
  • CSS2.1 released 7 June 2011
  • CSS3 ongoing work
    • Drafts published June 1999
    • Divided into several separate documents called "modules"
  • CSS4 refers to new 'level 4' modules

 

  • Allows same style sheet to be applied to many pages
  • Provides faster page loading due to less code (compared to old methods of individually styling html elements within the document)
  • Easier to maintain
  • Multiple Device Compatibility. Allows content to be optimized for multiple devices

*note!

Due to the nature of the following articles being posts within a WordPress environment, it has been necessary to code some of the example output within a separate iframe, to overcome the WordPress styling.

 

 

 

iframe source*

Syntax / Rules

CSS is made up of rules consisting of three parts:

  • Selector
    • HTML element that the style will be applied to
    • e.g. <h1>
  • Property
    • Style attribute of the element
    • e.g. color
  • Value
    • Corresponding value for the property
    • e.g. blue

 

 

The selector specifies which elements to style, and is followed by a declaration block that begins with a left curly brace { closes with a right curly brace } that contains the property/value pair declarations.

 

The property/value pair are separated by a colon and end with a semi colon.

 

Example:

h1color: blue; font-size: 2em; }

 

Save & refresh browser:

A very simple page

 

 

The syntax rules depicted using code:

iframe source*

Multiple Style Rules

Multiple style rules can be applied within the declaration block by ensuring each style declaration terminates with a semi-colon ;

 

The declarations can be placed on single or separate lines:

Save & refresh browser:

A fantastic heading styled on a single line.

A paragraph styled over multiple lines.

Comments

Comments are placed between /* and */

 

Can be on single or multiple lines.

 

Placement

There are four ways to apply CSS:

  • External stylesheet
  • Internal stylesheet
  • Inline style
  • Imported

 

External Stylesheet

 

This is the preferred method, promoting the separation of content from style.

 

A <link /> in the <head> section of the HTML document is used:

 

<head>

<link rel="stylesheet" href="style.css" type="text/css"  media="screen" />

</head>

 

 

With the following attributes:

Attribute Description Value
rel Specifies the relationship of the link between the document and the target URL, as defined in the href attribute "stylesheet"
href Specifies the location of the stylesheet URL; "./style.css"
type Specifies the MIME content type of the style language

(not required for HTML5 spec)

"text/css"
media Specifies the device type used to display the document all (default)

aural

braille

handheld

print

projection

screen

tv

tty

 

 

Internal Stylesheet

 

Utilises the <style> element within the <head> section of the HTML document:

 

<head>

<style type="text/css" media="screen">

body { background-color: black; }

h1 { color: #F00; }

p { color: #FFFFFF; }

</style>

</head>

 

 

Inline Style

 

Applies styling directly within the opening tag of an element using the 'style' attribute and then defining the rule declarations within quotes:

 

<p style="color: #FF0000; font-style: italic;" >This is my styled text.</p>

 

 

Imported

 

Imported stylesheets are used (usually within external stylesheets) in a similar manner to using the <link> element. The keyword @import is used before the stylesheet location and media type:

 

@import "style.css" screen, print, tv ;

 

The @import must have no spaces between the @ character and import, and must precede all other declarations. Thus, if in an external stylesheet it must be the first rule to be defined, and similarly it should be placed at the top of an internal stylesheet, like so:

 

<style>

@import "style.css" ;

ul { color: blue; }

... more rules go here ...

</style>

Selectors

Type Selectors, applied to a specific element type:

 

p { color: # F00; }

 

Universal Selector, matches any type of element:

 

* { background-color: blue; }

 

Descendant Selectors, match specific elements within another element. For example <li> elements that are only contained within a <div> element:

 

div li {color: #00F; }

 

Class Selectors, matches the class attribute of an element:

 

.topBox { border: solid 1px green; }

 

or to provide specific styling to <p> elements with the class attribute set to .topBox

 

p.topBox { color: #FFFF00; }

 

or apply multiple classes to an element:

 

.center { text-align: center; }

.bold {font-weight: bold; }

<p class="center bold"> <!-- note use of multiple classes -->

This para will be styled by the classes center and bold.

</p>

 

ID Selectors, match elements with a specific id attribute, utilising the hash/pound # symbol:

 

#uniqueID { color: #00F; }

 

ID selectors can also be made more specific when used in combination with element type selectors, e.g every <p> element with the id="uniqueID" attribute will be rendered green:

 

p#uniqueID { color: #0F0; }

 

Or use ID selectors as the foundation for descendant selectors. e.g. These <li> elements will only be rendered red when they lie within elements set with the id="uniqueID" attribute:

 

#uniqueID li { color: #F00; }

Save & refresh browser:

Here's some text!

This isn't styled

  • First item
  • Second item
  • Third item
  • Fourth item

 

 

Child Selectors, are applied only to direct child elements of the parent element. This example follows on from the previous, but note that the child selector rule is placed after the initial ID selector (setting the colour to green) and therefore over-rides the rule to render the direct <p> child element blue. Indirect elements are not affected by the child selector:

Save & refresh browser:

Direct child element. 

Here's some text!

Indirect child element.

 

 

Attribute Selectors, match elements with specific attributes

 

  • p[title] { color: #F00; }
Matches all elements with a title attribute
  • p[title = "exactly" ] { color: #0F0; }
Matches all elements whose title attribute has an exact value of "exactly"
  • p[title ~= exact ] { color: #00F; }
Matches all elements whose title attribute contains the word "exact"
  • p[title |= in ] { color: #90F; }
Matches all elements whose title attribute is exactly "in" or starts with "in-"

*note: hyphen on latter term

Save & refresh browser:

Red paragraph with a tooltip.

Paragraph without tooltip.

Green paragraph with a tooltip.

Blue paragraph with a tooltip.

Purple paragraph with a tooltip.

 

 

Grouping Selectors. The same style can be applied to multiple selectors by separating each selector with a comma ,

Save & refresh browser:

Main content goes here.

Box Model

In CSS a page consists of a set of elements rendered as rectangular boxes, nested inside one another.

 

Each element is represented as a box that consists of:

  • margins, outside the border
  • border
  • padding, inside the border
  • content, at the centre of the box

 

Notice the major bug (/headache) in the Internet Explorer box model. This causes a huge issue with developers having to code either separate stylesheets for IE or creating hacks to overcome IE's problems.

 

 

Given the following simple HTML:

 

The above html elements can be represented as a tree structure as follows:

 

Or as nested boxes:

 

Margins and Padding

Values can be set using the usual CSS units, e.g. px, em, ex, etc.

 

Specifying the values on their own, will give equal values to all four sides. e.g.:

 

p { margin: 5px;

border: 5px;

padding: 5px; }

 

Or to set individual values, use:

  • padding-top: 5px;
  • padding-right: 5px;
  • padding-bottom: 5px;
  • padding-left: 5px;
  • border-top: 5px;
  • border-right: 5px;
  • border-bottom: 5px;
  • border-left: 5px;
  • margin-top: 5px;
  • margin-right: 5px;
  • margin-bottom: 5px;
  • margin-left: 5px;

 

Shorthand examples:

  • 1 value sets all the same. margin: 1em ;
  • 2 pairs (top/bottom same, left/right same). margin: 1ex 0.5em ;
  • 3 values set in order: top, left/right pair, bottom. padding: 2ex 1em 4ex ;
  • 4 values Individually, in order TRBL. padding: 4ex 0.5em 5ex 3em ;

 

 

When an element has no borders, its margins and padding are adjacent, leaving them visually indistinguishable.

 

Also, Vertical margins collapse into a single gap. For example if two <p> elements both have their top and bottom margins set to 10px, there will only be 10px space between them, not 20px.

 

 

 

Negative margins can be used to offset or move/extend margin or padding or content outside it’s box container. This image depicts margins being set at -20px:

 

Borders

Three border properties can be specified:

  • border-style
    • required, without it no other border properties will have any effect
  • border-color
  • border-width

 

Or, all three can be set using the shorthand keyword border on its own:

 

Example:

#myDiv { border: solid 1px red ;}

h1 { border: groove 1em #00F; }

.myClass { border: outset 2pt #ABCDEF}

 

 

border-style

 

Sets the border style of the element

 

Property Description
none no border. equivalent of border-width:0;
solid Single solid line
dotted Series of dots
dashed Series of dashes
double Two solid lines
groove 3D grooved border
ridge 3D ridged border
inset 3D inset border
outset 3D outset border
hidden Same as none, except for border conflict resolution for table elements

 

Examples:

h1 { border-style: dotted ; }

p { border-style: solid ; }

 

Individual border edges can also be specified by defining the following properties:

  • border-top-style
  • border-right-style
  • border-bottom-style
  • border-left-style

Examples:

h1 { border-bottom-style: dashed ; }

p { border-left-style: solid ; }

 

 

border-color

 

Sets the border color of the element, in hex, RGB or colour name.

 

Examples:

h1 { border-color: #00F; }

p { border-color: rgb(63, 127, 255) ; }

.myClass { border-color: orange ; }

 

 

border-width

 

Sets the width of the border in px, pt or cm or it should be set to thin, medium or thick.

 

Examples:

h1 { border-width: 5px ; }

p { border-width: medium ; }

 

Individual border widths can also be specified by defining the following properties:

  • border-top-width
  • border-right-width
  • border-bottom-width
  • border-left-width

 

 

Shorthand properties

 

Each of the border properties can be specified with one to four values. These examples are for border-style property, but they same principle applies to border-width and border-color:

  • border-style:dotted solid double dashed;
    • top border is dotted
    • right border is solid
    • bottom border is double
    • left border is dashed
  • border-style:dotted solid double;
    • top border is dotted
    • right and left borders are solid
    • bottom border is double
  • border-style:dotted solid;
    • top and bottom borders are dotted
    • right and left borders are solid
  • border-style:dotted;
    • all four borders are dotted

Outlines

Outlines are very similar to borders but have the following major differences:

  • An outline does not take up space, i.e. they are outside of the element
  • Outlines do not have to be rectangular
  • Outline is always the same on all sides, i.e. you cannot specify different values for different sides of the element

 

 

Three outline properties can be specified:

  • outline-style
  • outline-color
  • outline-width

 

Or, all three can be set using the shorthand keyword outline on its own:

 

Example:

#myDiv { outline: solid 1px red ;}

h1 { outline: groove 1em #00F; }

.myClass { outline: outset 2pt #ABCDEF}

 

 

outline-style

 

Sets the outline style of the element

 

Property Description
none no border. equivalent of border-width:0;
solid Single solid line
dotted Series of dots
dashed Series of dashes
double Two solid lines
groove 3D grooved border
ridge 3D ridged border
inset 3D inset border
outset 3D outset border
hidden Same as none

 

Examples:

h1 { outline-style: dotted ; }

p { outline-style: solid ; }

 

 

outline-color

 

Sets the outline color of the element, in hex, RGB or colour name.

 

Examples:

h1 { outline-color: #00F; }

p { outline-color: rgb(63, 127, 255) ; }

.myClass { outline-color: orange ; }

 

 

outline-width

 

Sets the width of the outline in px, pt or cm or it should be set to thin, medium or thick.

 

Examples:

h1 { outline-width: 5px ; }

p { outline-width: medium ; }

Width & Height of an Element

When setting the width and height properties of an element with CSS, you just set the width and height of the content area.

 

To calculate the full size of an element, you must also add the padding, borders and margins.

 

Given the following CSS for an element, the total width equates to 640px:

width:500px;
padding:20px;
border:30px solid red;
margin:20px;

 

This is calculated as follows:

500px (width)

+ 40px (left + right padding)
+ 60px (left + right border)
+ 40px (left + right margin)

= 640px

Save & refresh browser:

My first Heading

Paragraph one

Paragraph two

Paragraph three

Block Boxes and Inline Boxes

HTML elements are either block level or inline and are accordingly rendered by the browser as block boxes or inline boxes.

 

Block boxes

  • Stretch across the full width of the containing element / page
  • Extend vertically down the page (as content is put in)
  • Can contain any other boxes
  • Often have margins, borders, and padding set
  • e.g.: <body>, <h1>, <p>, <ul>, <div>

 

 

Inline boxes

  • Contained inline within the parent block box element
  • Only big enough to fit their content
  • Can contain other inline elements, but not block boxes
  • Rarely have margins, borders or padding set
  • e.g.: <span>, <a>, <strong>, <em>, <code>

<div>

 

The <div> document division element is a block level element that acts as a container, encapsulating content and dividing the document into sections.

 

  • Starts a new line
  • Stretches across the width of its container
  • Acts as a container for other elements

 

CSS is generally applied to provide styling to a <div>, enabling all elements contained with the div to be styled at the same time.

 

Divs can be nested, and also as an example styled with CSS to say perform width adjustments or apply a specific font.

 

Save & refresh browser:

My first Heading

Paragraph one

Paragraph two

Paragraph three

<span>

The <span> element is an inline element that acts as a container for encapsulating content.

 

CSS is generally applied to provide styling to a <span>, enabling the content contained with the span to be styled individually.

 

A span can only contain other inline elements, and cannot contain block-level children.

 

<span> only works on inline content and should not be used for setting the width.

 

Save & refresh browser:

My first Heading

Paragraph one

Paragraph two

Paragraph three

Units

CSS supports absolute and relative units of measurement.

 

The 'em' is the preferred unit, being automatically scalable to the font being used. 1em is equal to the current font size. 2em means 2 times the size of the current font. E.g., if an element is displayed with a font of 12 pt, then '2em' is 24 pt.

 

Unit Description Example
% Specifies measurement as a percentage relative to another value, typically an enclosing element. p {font-size: 16pt; line-height: 125%;}
cm Specifies a measurement in centimeters. div {margin-bottom: 2cm;}
em Specifies a relative measurement for the height of a font in em spaces.

Because an em unit is equivalent to the size of a given font, if you assign a font to 12pt, each "em" unit would be 12pt; thus, 2em would be 24pt.

p {letter-spacing: 7em;}
ex Specifies a measurement relative to a font's x-height.

The x-height is determined by the height of the font's lowercase letter x.

p {font-size: 24pt; line-height: 3ex;}
in Specifies a measurement in inches. p {word-spacing: .15in;}
mm Specifies a measurement in millimeters. p {word-spacing: 15mm;}
pc Specifies a measurement in picas. A pica is equivalent to 12 points; thus, there are 6 picas per inch. p {font-size: 20pc;}
pt Specifies a measurement in points. A point is defined as 1/72nd of an inch. body {font-size: 18pt;}
px Specifies a measurement in screen pixels. p {padding: 25px;}

Dimensions

The dimensions of an element can be set using the following properties:

 

Property Description Value
width Specifies the width of an element length 

%

auto

inherit

min-width Specifies the minimum width of an element length 

%

auto

inherit

max-width Specifies the maximum width of an element length 

%

auto

inherit

height Specifies the height of an element length 

%

auto

inherit

min-height Specifies the minimum height of an element length 

%

auto

inherit

max-height Specifies the maximum height of an element length 

%

auto

inherit

 

Where length and % are the values specified as per the units section above.

 

Save & refresh browser:

A heading element with a height of 100px.

A heading element with a min-height of 200px.

A heading element with a max-height of 10px.

A heading element with a width of 500px.

A heading element with a min-width of 700px.

A heading element with a max-width of 100px.

Colours

Colours can be defined in any of the following:

  • Hex code
    • #RRGGBB
    • p { color: #00FF00; }
  • Short Hex code
    • #RGB
    • p { color: #F00; }
  • RGB %
    • rgb(rrr%,ggg%,bbb%)
    • p { color: rgb(10%, 40%, 60%) ; }
  • RGB Absolute
    • rgb(rrr,ggg,bbb)
    • p {color: rgb(0, 127, 255) ;}
  • Keyword
    • red, green, blue, etc
    • p { color: blue; }

 

*note: Brits beware! use american spelling for color !

 

Browser safe color chart

000000 000033 000066 000099 0000CC 0000FF
003300 003333 003366 003399 0033CC 0033FF
006600 006633 006666 006699 0066CC 0066FF
009900 009933 009966 009999 0099CC 0099FF
00CC00 00CC33 00CC66 00CC99 00CCCC 00CCFF
00FF00 00FF33 00FF66 00FF99 00FFCC 00FFFF
330000 330033 330066 330099 3300CC 3300FF
333300 333333 333366 333399 3333CC 3333FF
336600 336633 336666 336699 3366CC 3366FF
339900 339933 339966 339999 3399CC 3399FF
33CC00 33CC33 33CC66 33CC99 33CCCC 33CCFF
33FF00 33FF33 33FF66 33FF99 33FFCC 33FFFF
660000 660033 660066 660099 6600CC 6600FF
663300 663333 663366 663399 6633CC 6633FF
666600 666633 666666 666699 6666CC 6666FF
669900 669933 669966 669999 6699CC 6699FF
66CC00 66CC33 66CC66 66CC99 66CCCC 66CCFF
66FF00 66FF33 66FF66 66FF99 66FFCC 66FFFF
990000 990033 990066 990099 9900CC 9900FF
993300 993333 993366 993399 9933CC 9933FF
996600 996633 996666 996699 9966CC 9966FF
999900 999933 999966 999999 9999CC 9999FF
99CC00 99CC33 99CC66 99CC99 99CCCC 99CCFF
99FF00 99FF33 99FF66 99FF99 99FFCC 99FFFF
CC0000 CC0033 CC0066 CC0099 CC00CC CC00FF
CC3300 CC3333 CC3366 CC3399 CC33CC CC33FF
CC6600 CC6633 CC6666 CC6699 CC66CC CC66FF
CC9900 CC9933 CC9966 CC9999 CC99CC CC99FF
CCCC00 CCCC33 CCCC66 CCCC99 CCCCCC CCCCFF
CCFF00 CCFF33 CCFF66 CCFF99 CCFFCC CCFFFF
FF0000 FF0033 FF0066 FF0099 FF00CC FF00FF
FF3300 FF3333 FF3366 FF3399 FF33CC FF33FF
FF6600 FF6633 FF6666 FF6699 FF66CC FF66FF
FF9900 FF9933 FF9966 FF9999 FF99CC FF99FF
FFCC00 FFCC33 FFCC66 FFCC99 FFCCCC FFCCFF
FFFF00 FFFF33 FFFF66 FFFF99 FFFFCC FFFFFF

Backgrounds

HTML elements can have backgrounds set using the following CSS properties:

  • background
  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position

 

 

background

 

Shorthand approach, setting the other properties (in descending order from above) as follows:

 

Syntax:

body { background: color image repeat attachment position ; }

 

Example:

body { background: #0000FF url('path/myImage.png') no-repeat fixed top left ; }

 

This would give a blue background to the <body> element and place a non-repeating fixed image in the top left corner.

 

 

background-color

 

Sets the background color of the element, in hex, RGB or colour name.

 

Examples:

h1 { background-color: #00F; }

p { background-color: rgb(63, 127, 255) ; }

.myClass { background-color: orange ; }

 

 

background-image

 

Specifies a background image to be used on the element. It's default setting is set to repeat, to cover the whole element.

 

Example:

#myDiv { background-image: url('/images/logo.png') ; }

 

*note: the image path is relative to the stylesheet

 

 

background-repeat

 

Specifies whether the background image repeats horizontally or vertically.

 

Possible values are:

  • repeat
    • Specifies that the image will be repeated both horizontally and vertically. Default.
  • repeat-x
    • Specifies that the image will only be repeated horizontally
  • repeat-y
    • Specifies that the image will only be repeated vertically
  • no-repeat
    • Specifies that the image will not be repeated
  • inherit
    • Specifies that the setting is inherited from the parent element

 

Example:

body {background-image: url('/images/bigImage.png') ; background-repeat: no-repeat ; }

 

 

 

background-attachment

 

Specifies whether the background is fixed or scrolls with the page.

 

Possible values are:

  • scroll
    • background scrolls with the element. Default
  • fixed
    • background is fixed in the viewport
  • local
    • background scrolls with the element's content

 

Example:

body {background-image: url('/images/bigImage.png') ; background-repeat: no-repeat ; background-attachment: fixed ; }

 

 

background-position

 

Specifies the starting position of the background image

 

Value Description
left top 

left center

left bottom

center top

center center

center bottom

right top

right center

right bottom

The other value will be set to center if only one keyword is specified
x% y% x% is the horizontal position 

y% is the vertical position

top left is 0% 0%

bottom right is 100% 100%

The other value will be set to 50% if only one value is specified

xpos ypos xpos is the horizontal position 

ypos is the vertical position

Units can be px, cm or any other CSS units

Units and % can be mixed

The other value will be set to 50% if only one value is specified

inherit  Specifies that the setting is inherited from the parent element

 

 

Example:

 

body { background-image: url('/images/forest.png') ; background-repeat: no-repeat ; background-position: right top ; }

id Selector

  • Styles a single unique element
  • Utilises the id attribute of an element
  • Defined with a # followed by the value assigned to the id attribute

 

Save & refresh browser:

A very simple page

A line of text.

 

A line of text.

 

A line of text.

 

A line of text.

 

A line of text.

class Selector

  • Styles a group of elements
  • Utilises the class attribute of an element
  • Defined with a . followed by the value assigned to the class attribute

 

Save & refresh browser:

A very simple page

A line of text.

 

A line of text.

 

A line of text.

 

A line of text.

 

A line of text.

 

 

More specific elements can also styled by specifying only parent elements with the class defined. In this example only <p> elements have the rule applied:

Save & refresh browser:

A very simple page

A line of text.

 

A line of text.

 

A line of text.

 

A line of text.

 

A line of text.

Fonts

Fonts come in two main styles:

  • Sans-Serif
  • Serif

 

Serifs are the small decorations on the font characters:

Sans-Serif Serif

 

Fonts are defined by setting their properties:

 

Property Description Value
font-style Specifies the style to apply to the font normal, italic, oblique
font-variant Converts lower-case characters to capitals, but in a smaller font size normal, small-caps
font-weight Specifies how bold or light a font should be normal, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, 900.
font-size Specifies the size of the font xx-small, x-small, small, medium, large, x-large, xx-large, smaller, larger, size in pixels or in %
font-family Specifies the actual font face to apply family-name. e.g."verdana", "arial", "courier" etc.
generic-family. e.g. "serif", "sans-serif", "cursive", "fantasy", "monospace".
font Shorthand version to set all properties e.g. font: Arial 17px bold italic

 

 

The font properties can be set in a single style declaration, by specifying the attributes in the following order:

  1. font-style
  2. font-variant
  3. font-weight
  4. font-size/line-height *
  5. font-family *

values are required. If one of the other values is missing, the default values will be inserted, if any.

 

Save & refresh browser:

My paragraph text

 

 

 

A selection of commonly used web-safe font-families. Multiple values ensure a fallback to a value that the browser can pick if no other fonts are available:

 

 

Serif Fonts

Georgia, serif
"Palatino Linotype", "Book Antiqua", Palatino, serif
"Times New Roman", Times, serif

Sans-Serif Fonts

Arial, Helvetica, sans-serif
"Arial Black", Gadget, sans-serif
"Comic Sans MS", cursive, sans-serif
Impact, Charcoal, sans-serif
"Lucida Sans Unicode", "Lucida Grande", sans-serif
Tahoma, Geneva, sans-serif
"Trebuchet MS", Helvetica, sans-serif
Verdana, Geneva, sans-serif

Monospace Fonts

"Courier New", Courier, monospace
"Lucida Console", Monaco, monospace

Text

Text is styled using the following properties:

 

Property Description Value
color Specifies the colour of the text User defined
direction Specifies the text direction ltr (default)

rtl

letter-spacing Specifies spacing between characters User defined
word-spacing Specifies spacing between words User defined
text-indent Specifies indentation amount User defined
text-align Aligns the text Left, center, right, justify
text-decoration Specifies the decoration to be added underline, strikethrough, overline
text-transform Specifies whether to capitalise or convert to upper or lower case none, uppercase, lowercase, capitalize
white-space Specifies white space within an element normal, nowrap, pre, pre-line, pre-wrap
text-shadow Specifies text shadowing h-shadow px (*required)

v-shadow px (*required)

blur

color

vertical-align Specifies the vertical alignment of an element length

%

baseline

sub

super

top

text-top

middle

bottom

text-bottom

 

Save & refresh browser:

A red colored paragraph of text.

This text runs from right to left.

This paragraph's letters are spaced out by 10px.

This paragrpah's words are spaced out by 20px.

The first line of an indented parapgraph.

This text is right aligned.

This paragraph has been struck through!

THE TEXT IN THIS PARAGRAPH HAS BEEN TRANSFORM TO UPPERCASE.

The whitespace in this paragraph has been set to pre

and as you can see obeys the
same rules as the <pre> tag.

A red shadow has been applied to this text.

This paragraph contains this text which I've made appear above the rest of the bounding element.

Links

Links can be styled using the following pseudo class selectors:

  • a:link
    • Link has not been visited, mouse pointer not hovering over
  • a:visited
    • Link has been visited, mouse pointer not hovering over
  • a:hover
    • Mouse pointer hovering over
  • a:active
    • Link is being clicked

 

The order in which they are defined is strictly mandated to follow the LVHA order:

 

a:link { color:#FF0000; }
a:visited { color:#0000FF; }
a:hover { color:#00FF00; }
a:active { color:#FF00FF; }

Lists

Lists can be styled using the following CSS properties:

 

  • list-style
  • list-style-image
  • list-style-position
  • list-style-type

 

Property Description Value
list-style Shorthand to specify all properties "inside square"
list-style-image Specifies an image for the marker User defined URL
list-style-position Specifies whether marker appears inside or outside the containing element none

inside

outside

list-style-type Specifies the type of list item:

Unordered lists

Ordered lists

none

circle

disc *

square

--------

decimal *

decimal-leading-zero

lower-alpha

upper-alpha

lower-roman

upper-roman

lower-greek

lower-latin

 

  1. 1st RULE: You do not talk about FIGHT CLUB.
  2. 2nd RULE: You DO NOT talk about FIGHT CLUB.
  3. 3rd RULE: If someone says "stop" or goes limp, taps out the fight is over.

 

  • 4th RULE: Only two guys to a fight.
  • 5th RULE: One fight at a time.
  • 6th RULE: No shirts, no shoes.

 

  • 7th RULE: Fights will go on as long as they have to.
  • 8th RULE: If this is your first night at FIGHT CLUB, you HAVE to fight.

Tables

The following specific table styling properties can be used to control how a table is rendered by the browser:

Property Description Value
border-collapse  Specifies whether borders are collapsed into a single border or separated into separate borders collapse 

separate

inherit

border-spacing *note: ONLY applies to separated cells, see above 

Specifies the distance between borders of adjacent cells

 

Single value set both horizontal and vertical spacing

Two values specify horizontal then vertical spacing

Cannot use negative values

User defined
empty-cells Specifies if border should be shown if cell is empty hide 

show

inherit

table-layout Specifies the table layout algorithm auto 

fixed

inherit

 

Example:

Save & refresh browser:

 

 

 

Table cells, rows and columns have no margins, only padding.

 

vertical-align sets the vertical position of cell contents.

*note: see the Text vertical-align table for details of values for this property)

Pseudo Classes / Elements

Pseudo class selectors consist of the normal selector followed by a colon : and the desired pseudo class selector.

 

Syntax:

selector:pseudo-class { property: value; }

 

Example:

a:hover { color: #FF00FF; }

 

This will style <a> link elements to be coloured red upon mouse pointer hover.

 

 

CSS classes can also be used with pseudo-classes:

selector.class:pseudo-class { property: value; }

 

Common Pseudo Class Selectors:

Property Description Example
:link Styles unvisited links a:link
:visited Styles visited links a:visited
:hover Styles elements upon mouse over a:hover
:active Styles active element a:active
:first-child Styles first child of the specified selector li:first-child
:last-child Styles last child of the specified selector li:last-child
:first-line Styles first line of the specified selector p:first-line
:first-letter Styles first letter of the specified selector p:first-letter
:before Styles content before the specified selector p:before
:after Styles content after the specified selector p:after
:lang(language) Styles all elements with specified lang attribute p:lang(en)

 

Example:

Save & refresh browser:

Positioning

The four methods of setting the position property of a box are:

  • static
  • relative
  • absolute
  • fixed

 

 

Static

 

  • Default
  • Can be explicitly set { position: static; }
  • Each block starts a new line, just after end of previous block
  • Occupies full width
  • Normal flow down the page

Save & refresh browser:

 

 

 

 

 

Absolute

 

  • Positioned according to its own properties
  • Outside of normal flow
  • Effectively sits on its own layer on top of the rest of the page
  • { position:absolute; } then defined values for the top, right, bottom, left properties

Save & refresh browser:

 

 

 

Relative

 

  • Positions the box to where it would have been positioned if statically positioned
  • The remaining empty space where it would have been is still preserved
  • Mainly used as a container for absolute positioned block and floats
  • { position:relative; } then defined values for the top, right, bottom, left properties

Save & refresh browser:

 

 

 

Fixed

 

  • Doesn't move if the rest of the page scrolls
  • Positioning is offset from the edges of the viewport
  • Unrelated to other objects

Save & refresh browser:

 

 

 

Relative + Absolute

 

By applying relative positioning on a containing element, any elements within that container will be positioned relative to it.

IMPORTANT! The containing box must be relative to have the contained boxes positioned relative to it.

 

Therefore any absolute positioned elements within the container are relative to the container:

Save & refresh browser:

Float

Float allows an element to be positioned to the left or the right of its containing box's padding.

 

Other content flows around the floated box.

 

Property Description Value
float Specifies whether a box should be floated left 

right

none

inherit

 

 

Multiple floated boxes align against each other, horizontally, if there's room, or down the page otherwise.

 

Syntax:

#myBox { float: left; }

 

*note: Open this article in a tab on its own to see the 4th box floating next to the 3rd

Containing Box

 

 

Here's an example of an image being floated within its containing box and the rest of the text content being wrapped around it:

Save & refresh browser:

iframe source*

 

 

 

clear

 

As can be seen in the above, elements after the floating element will flow around it.

 

This can be avoided by using the clear property.

 

Syntax:

#myDiv { clear: right; }

 

 

Property Description Value
clear Specifies which sides of the containing element other floating elements are not allowed both 

left

right

none

inherit

 

 

Notice line 9 now has the clear property defined on the <p> element:

Save & refresh browser:

iframe source*

Display

The display property specifies how / if an element should be displayed

 

With the following values assigned to the display property:

Value Description
hidden Hides the element, but it still takes up the same space
block Displays the element as a block element
inline Displays the element as an inline element

 

 

Save & refresh browser:

This first list has the display property set as none: 

So it won't be displayed!

 

Using {display:block;} to make a

span (inline) element

display as a block element!

 

Now using {display:inline;} to make block <li> elements display like inline elements:

  1. Honda
  2. Yamaha
  3. Ducati

Visibility

The visibility property is similar to the display property, but only specifies if an element should be displayed

 

With the following values assigned to the visibility property:

Value Description
visible Box is visible. Default value
hidden Box is not visible, but still occupies the same space
collapse Only used on table elements 

Removes a row or column, but does not affect layout

 

Example:

Save & refresh browser:

A normal visible heading.

Followed by an invisible hidden heading!

And now some text occupying the space as though the <h2> heading were still there!

Aligning

An element can be aligned using the left and right properties along with the position property.

 

For instance, set an element's {position:absolute;} then set it's distance from either the left or right edges using values assigned for these properties:

Save & refresh browser:

iframe source*

Centering

To center a block within its parent, equal left and right margins should be set:

 

#myDiv {margin:1em 8em; }

 

If a specific width is required, the individual margins should be set to auto:

 

#myDiv {margin-left:auto; margin-right:auto; width:300px;}

 

Save & refresh browser:

iframe source*

Layers

Layers are created using the z-index property, which sets the stacking order for an element.

 

Higher z-index values are placed above those with lower values, but only works on positioned elements (e.g. position:absolute, position:relative, or position:fixed).

 

Save & refresh browser:

But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness.

No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful.

Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure.

To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"

Opacity

The opacity property is used to specify how opaque (/transparent) an element should be.

 

Values range from 0.0 to 1.0 with a lower value making the element more transparent.

 

Earlier versions of IE require (<= IE8) use filter:alpha(opacity=x), where x is specified as a value from 0 - 100, with a lower value making the element more transparent.

 

Save & refresh browser:

But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness.

 

No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful.

Image Sprites

Image sprites are used a technique to load multiple images within a single image and therefore only a single web request and then specifying an area of the image which is known as a sprite.

 

An image sprite will have a number of smaller images within specific areas, such as this example:

 

 

Specific image sections are picked out using co-ordinates.

 

In the above image and following example, the height for each sprite within the image is defined as 95px;

 

Left 0px, Top 0px, represents the top left corner.

 

The width of the first image within the sprite is 77px.

 

Therefore to select just the first image, an area is defined as being 0px from the left of the image with a width of 77px, and having a background image with left top coordinates of 0 0.

 

The next sprite is then defined to start at 78px from the left with a width of 98px, and having a background image with left top coordinates of -77px 0.

 

*Note: the left coordinate is now being defined as a negative number, this is because the new coordinate we want to see is to the right of the initial image and since the background-position is set using top left coordinates we need to specify negative values relative to the top left. Thus -77px is equivalent to saying right 77px. Similarly sprites further down the image use negative values, and therefore -101px represents the sprite 101px from the top of the image. Confusing, yes, but that's the way it is!

 

The third sprite is then defined to start at 177px from the left with a width of 78px, and having a background image with left top coordinates of -178px 0.

 

Hover effects can be added by defining the lower set of sprites simply placed at the lower coordinate -101px.

 

Save & refresh browser:

iframe source*

@ Rules

  • @import imports another stylesheet into the current stylesheet
  • @charset specifies the character set the stylesheet is using
  • @font-face specifies a font-face to be used

 

@import

 

Imported stylesheets are used (usually within external stylesheets) in a similar manner to using the <link> element. The keyword @import is used before the stylesheet location and media type:

 

@import “style.css” screen, print, tv ;

or

@import url("style.css") ;

 

The @import must have no spaces between the @ character and import, and must precede all other declarations. Thus, if in an external stylesheet it must be the first rule to be defined, and similarly it should be placed at the top of an internal stylesheet, like so:

 

<style>

@import “style.css” ;

ul { color: blue; }

… more rules go here …

</style>

 

The @import rule allows a modular approach to developing styles for a site, whereby various style sheets can be included wherever required. For instance, a master stylesheet can be created for a whole site and perhaps a seasonal stylesheet used that imports the master stylesheet then applies specific styling that overrides the master stylesheet to give the required seasonal styling.

 

 

@charset

 

Used to specify the character set the stylesheet is written in.

 

The @charset rule must be written right at the beginning of the style sheet without even a space before it. The value is held in quotes and should be one of the standard character-sets.

 

<style type="text/css">

<!--

@charset "iso-8859-1"
.......other CSS rules .....

-->

</style>

 

 

@font-face

 

Can be used to describe a font face to be used, or to define the location of a font for download.

 

<style tyle="text/css">

<!--

@font-face {

font-family: "Delicious";
src: url("https://example.com/fonts/Delicious.ttf");

}
@font-face {

font-family: Delicious;
src: local ("Delicious"),
url("https://www.example.com/fonts/delicious.tt")
format("truetype");
unicode-range: U+??,U+100-220;
font-size: all;
font-family: sans-serif;

}

-->

</style>

!important

The !important rule specifies that the specific rule it is appended to, will always be applied no matter where it lies within the cascade of the stylesheet(s).

 

For instance, say you had a master style sheet with a rule:

 

p { color:#FF0000; }

 

and you then used an @import to style a specific page, followed by a new rule to override the original p style:

 

@import 'style.css' ;

p { color:#0000FF; }

 

It would then be expected that the new rule would override the master's style.css p rule and colour p elements blue (#0000FF) for that page.

 

However, the !important directive can be applied within the master style.css to ensure it is always applied, no matter if a new rule is defined for it, by appending !important to it like so:

 

p { color:#FF0000 !important; }

 

Now, any future definitions of the p element styling will not have any effect and the original p styling will always be applied.

Media Types

Media types allow different layouts for different devices, such as screen, print, projection, tv, to be specified.

 

The @media keyword is followed by the media type keyword that you want the rules to apply to.

 

The following CSS will render <p> elements with a font-size of 16px and a font-weight of bold for the screen, or 10px and bold if printed

 

@media screen {

p { font-size:16px; }

}

@media print {

p { font-size:10px; }

}

@media screen, print {

p { font-weight:bold; }

}

 

 

 Type Description 
all All media types
aural Speech & sound synthesizers
braille Braille tactile feedback devices
embossed Paged braille printers
handheld Small screen handheld devices
print Printers
projection Projected presentations, slides
screen Computer screens
tty Fixed pitch character grid; teletypes, terminals
tv Televisions

@page

The @page rule specifies how a document is formatted within a rectangular area -- the page box -- that has a finite width and height.

 

  • The size property defines the dimensions of the page
  • The margin property defines the margins of the page
    • All margins can be defined using the keyword: margin
    • Or individual margins set: margin-top, margin-bottom, margin-left, and margin-right

 

@page { size:A4; margin:2cm; }

 

 

Values for the size property:

Value Description
auto Page box set to size & orientation of target sheet
landscape Overrides target's orientation. Page box is same as target & longer side is horizontal
portrait Overrides target's orientation. Page box is same as target & shorter side is horizintal
length Values create an absolute sized box. If one value specified, it sets both width & height 

values can be in general units or recognized page sizes, e.g. A4

 

It is possible to create a named page layout by simply adding the name of your choice after the @page rule. e.g:

 

@page { size : portrait ; }
@page rotated { size : landscape ; }
table { page : rotated ; }

 

The above renders all tables in the document on landscape pages.

 

 

Left, right, and first pages:

When printing double-sided documents, the page boxes on left and right pages should be different. This can be expressed through two CSS pseudo-classes as follows:

@page :left { margin-left: 4cm; margin-right: 3cm; }

@page :right { margin-left: 3cm; margin-right: 4cm; }

 

 

You can also specify the style for the first page of a document with the :first pseudo-class:

 

@page { margin: 2cm } /* All margins set to 2cm */

@page :first { margin-top:10cm; } /* Top margin on first page 10cm */

 

 

Controlling pagination:

 

Unless you specify otherwise, page breaks occur only when the page format changes or when the content overflows the current page box. To otherwise force or suppress page breaks, use the page-break-before, page-break-after, and page-break-inside properties.

 

Both the page-break-before and page-break-after properties accept the auto, always, avoid, left,and right keywords.

 

Value Description
auto Browser generates page breaks as required. Default
always Forces page break before or after the element
avoid Suppresses page break immediately before or after the element
left Force page break so element is rendered on a left hand page
right Force page break so element is rendered on a right hand page

 

 

For instance, if your <h1> elements start new chapters, with sections denoted by <h2> and you'd like each chapter to start on a new, right-hand page, but you don't want section headers to be split across a page break from the subsequent content, this can be achieved by using the following rule:

 

h1 { page-break-before : right ; }
h2 { page-break-after : avoid ; }

 

 

Use only the auto and avoid values with the page-break-inside property. If you prefer that your tables not be broken across pages if possible, you would write the rule:

 

table { page-break-inside : avoid ; }

 

 

Controlling widows and orphans:
In typographic lingo, orphans are those lines of a paragraph stranded at the bottom of a page due to a page break, while widows are those lines remaining at the top of a page following a page break. Generally, printed pages do not look attractive with single lines of text stranded at the top or bottom. Most printers try to leave at least two or more lines of text at the top or bottom of each page.

 

  • The orphans property specifies the minimum number of lines of a paragraph that must be left at the bottom of a page.
  • The widows property specifies the minimum number of lines of a paragraph that must be left at the top of a page.

Here is the example to create 4 lines at the bottom and 3 lines at the top of each page:

 

@page { orphans:4; widows:2; }

Cursors

The cursor property allows a specific cursor type to be displayed:

 

Value Description
auto Depends on context area
crosshair Crosshair, or plus sign
default Arrow
pointer Pointing hand
move North, east south, west arrows
e-resize Horizontal east, west arrows
ne-resize Diagonal north east arrows
nw-resize Diagonal north west arrows
n-resize Vertical north south arrows
se-resize Diagonal south east arrows
sw-resize Diagonal south west arrows
s-resize Vertical north south arrows
w-resize Horizontal east west arrows
text The I bar
wait Spinning circle or Hour glass
help Question mark or balloon
<url> source of cursor image file

 

Example showing all the above:

Save & refresh browser:

Move the mouse over the words to see the cursor change:
 

Auto
Crosshair
Default
Pointer
Move
e-resize
ne-resize
nw-resize
n-resize
se-resize
sw-resize
s-resize
w-resize
text
wait
help
image

Overflow

If an element's contents are larger than the space allocated (e.g. if height / width are too small) the overflow property can be used to tell the browser how to handle any overflowed content.

 

Value Description
auto Same as scroll, but scrollbars are only added if needed
hidden Content of the element is cut off at the border and no scrollbars are visible
scroll Containing element size stays the same, but scrollbars are added to allow the use to see the content
visible Allows content to overflow the borders of its containing element

 

Example:

Save & refresh browser:

Example of scroll value:

I am going to keep lot of content here just to show you how scrollbars works if there is an overflow in an element box. This provides your horizontal as well as vertical scrollbars.

 

Example of auto value:

I am going to keep lot of content here just to show you how scrollbars works if there is an overflow in an element box. This provides your horizontal as well as vertical scrollbars.

Selector Reference

Selector Example Example description
.class .intro Selects all elements with class="intro"
#id #firstname Selects the element with id="firstname"
* * Selects all elements
element p Selects all <p> elements
element,element div, p Selects all <div> elements and all <p> elements
element element div p Selects all <p> elements inside <div> elements
element>element div > p Selects all <p> elements where the parent is a <div> element
element+element div + p Selects all <p> elements that are placed immediately after <div> elements
element1~element2 p ~ ul Selects every <ul> element that are preceded by a <p> element
[attribute] [target] Selects all elements with a target attribute
[attribute=value] [target=_blank] Selects all elements with target="_blank"
[attribute~=value] [title~=flower] Selects all elements with a title attribute containing the word "flower"
[attribute|=value] [lang|=en] Selects all elements with a lang attribute value starting with "en"
[attribute^=value] a[href^="https"] Selects every <a> element whose href attribute value begins with "https"
[attribute$=value] a[href$=".pdf"] Selects every <a> element whose href attribute value ends with ".pdf"
[attribute*=value] a[href*="w3schools"] Selects every <a> element whose href attribute value contains the substring "w3schools"
:active a:active Selects the active link
::after p::after Insert something after the content of each <p> element
::before p::before Insert something before the content of each <p> element
:checked input:checked Selects every checked <input> element
:disabled input:disabled Selects every disabled <input> element
:empty p:empty Selects every <p> element that has no children (including text nodes)
:enabled input:enabled Selects every enabled <input> element
:first-child p:first-child Selects every <p> element that is the first child of its parent
::first-letter p::first-letter Selects the first letter of every <p> element
::first-line p::first-line Selects the first line of every <p> element
:first-of-type p:first-of-type Selects every <p> element that is the first <p> element of its parent
:focus input:focus Selects the input element which has focus
:hover a:hover Selects links on mouse over
:in-range input:in-range Selects input elements with a value within a specified range
:invalid input:invalid Selects all input elements with an invalid value
:lang(language) p:lang(it) Selects every <p> element with a lang attribute equal to "it" (Italian)
:last-child p:last-child Selects every <p> element that is the last child of its parent
:last-of-type p:last-of-type Selects every <p> element that is the last <p> element of its parent
:link a:link Selects all unvisited links
:not(selector) :not(p) Selects every element that is not a <p> element
:nth-child(n) p:nth-child(2) Selects every <p> element that is the second child of its parent
:nth-last-child(n) p:nth-last-child(2) Selects every <p> element that is the second child of its parent, counting from the last child
:nth-last-of-type(n) p:nth-last-of-type(2) Selects every <p> element that is the second <p> element of its parent, counting from the last child
:nth-of-type(n) p:nth-of-type(2) Selects every <p> element that is the second <p> element of its parent
:only-of-type p:only-of-type Selects every <p> element that is the only <p> element of its parent
:only-child p:only-child Selects every <p> element that is the only child of its parent
:optional input:optional Selects input elements with no "required" attribute
:out-of-range input:out-of-range Selects input elements with a value outside a specified range
:read-only input:read-only Selects input elements with the "readonly" attribute specified
:read-write input:read-write Selects input elements with the "readonly" attribute NOT specified
:required input:required Selects input elements with the "required" attribute specified
:root :root Selects the document's root element
::selection ::selection Selects the portion of an element that is selected by a user
:target #news:target Selects the current active #news element (clicked on a URL containing that anchor name)
:valid input:valid Selects all input elements with a valid value
:visited a:visited Selects all visited links

source: https://www.w3schools.com/cssref/css_selectors.asp