Welcome to FixHub, If you need design please contact us

CSS basic tutorial

 

CSS Introduction

Next ❯

CSS is the language we use to style an HTML document.

CSS describes how HTML elements should be displayed.

This tutorial will teach you CSS from basic to advanced.

Examples in Each Chapter

This CSS tutorial contains hundreds of CSS examples.

With our online editor, you can edit the CSS, and click on a button to view the result.

CSS Example

body {
  background-color: lightblue;
}

h1 {
  color: white;
  text-align: center;
}

{
  font-family: verdana;
  font-size: 20px;
}

Click on the "Try it Yourself" button to see how it works.

CSS Introduction

CSS is the language we use to style a Web page.


What is CSS?

  • CSS stands for Cascading Style Sheets
  • CSS describes how HTML elements are to be displayed on screen, paper, or in other media
  • CSS saves a lot of work. It can control the layout of multiple web pages all at once
  • External stylesheets are stored in CSS files

CSS Demo - One HTML Page - Multiple Styles!

Here we will show one HTML page displayed with four different stylesheets. Click on the "Stylesheet 1", "Stylesheet 2", "Stylesheet 3", "Stylesheet 4" links below to see the different styles:

Why Use CSS?

CSS is used to define styles for your web pages, including the design, layout and variations in display for different devices and screen sizes.

CSS Example

body {
  background-color: lightblue;
}

h1 {
  color: white;
  text-align: center;
}

{
  font-family: verdana;
  font-size: 20px;
}


CSS Solved a Big Problem

HTML was NEVER intended to contain tags for formatting a web page!

HTML was created to describe the content of a web page, like:

<h1>This is a heading</h1>

<p>This is a paragraph.</p>

When tags like <font>, and color attributes were added to the HTML 3.2 specification, it started a nightmare for web developers. Development of large websites, where fonts and color information were added to every single page, became a long and expensive process.

CSS Saves a Lot of Work!

The style definitions are normally saved in external .css files.

With an external stylesheet file, you can change the look of an entire website by changing just one file!

 

CSS Syntax

A CSS rule consists of a selector and a declaration block.

CSS Syntax

CSS selector

The selector points to the HTML element you want to style.

The declaration block contains one or more declarations separated by semicolons.

Each declaration includes a CSS property name and a value, separated by a colon.

Multiple CSS declarations are separated with semicolons, and declaration blocks are surrounded by curly braces.

Example

In this example all <p> elements will be center-aligned, with a red text color:

{
  color
: red;
  text-align
: center;
}

Example Explained

  • p is a selector in CSS (it points to the HTML element you want to style: <p>).
  • color is a property, and red is the property value
  • text-align is a property, and center is the property value

You will learn much more about CSS selectors and CSS properties in the next chapters!

CSS Selectors

A CSS selector selects the HTML element(s) you want to style.

CSS Selectors

CSS selectors are used to "find" (or select) the HTML elements you want to style.

We can divide CSS selectors into five categories:

  • Simple selectors (select elements based on name, id, class)
  • Combinator selectors (select elements based on a specific relationship between them)
  • Pseudo-class selectors (select elements based on a certain state)
  • Pseudo-elements selectors (select and style a part of an element)
  • Attribute selectors (select elements based on an attribute or attribute value)

This page will explain the most basic CSS selectors.


The CSS element Selector

The element selector selects HTML elements based on the element name.

Example

Here, all <p> elements on the page will be center-aligned, with a red text color: 

{
  text-align: center;
  color: red;
}

The CSS id Selector

The id selector uses the id attribute of an HTML element to select a specific element.

The id of an element is unique within a page, so the id selector is used to select one unique element!

To select an element with a specific id, write a hash (#) character, followed by the id of the element.

Example

The CSS rule below will be applied to the HTML element with id="para1": 

#para1 {
  text-align: center;
  color: red;
}

Note: An id name cannot start with a number!

 

The CSS class Selector

The class selector selects HTML elements with a specific class attribute.

To select elements with a specific class, write a period (.) character, followed by the class name.

Example

In this example all HTML elements with class="center" will be red and center-aligned: 

.center {
  text-align: center;
  color: red;
}

You can also specify that only specific HTML elements should be affected by a class.

Example

In this example only <p> elements with class="center" will be red and center-aligned: 

p.center {
  text-align: center;
  color: red;
}

HTML elements can also refer to more than one class.

Example

In this example the <p> element will be styled according to class="center" and to class="large": 

<p class="center large">This paragraph refers to two classes.</p>

Note: A class name cannot start with a number!


The CSS Universal Selector

The universal selector (*) selects all HTML elements on the page.

Example

The CSS rule below will affect every HTML element on the page: 

{
  text-align: center;
  color: blue;
}

The CSS Grouping Selector

The grouping selector selects all the HTML elements with the same style definitions.

Look at the following CSS code (the h1, h2, and p elements have the same style definitions):

h1 {
  text-align: center;
  color: red;
}

h2 {
  text-align: center;
  color: red;
}

{
  text-align: center;
  color: red;
}

It will be better to group the selectors, to minimize the code.

To group selectors, separate each selector with a comma.

Example

In this example we have grouped the selectors from the code above: 

h1, h2, p {
  text-align: center;
  color: red;
}


All CSS Simple Selectors

Selector

Example

Example description

#id

#firstname

Selects the element with id="firstname"

.class

.intro

Selects all elements with class="intro"

element.class

p.intro

Selects only <p> elements with class="intro"

*

*

Selects all elements

element

p

Selects all <p> elements

element,element,..

div, p

Selects all <div> elements and all <p> elements

 

 

How To Add CSS

When a browser reads a style sheet, it will format the HTML document according to the information in the style sheet.

Three Ways to Insert CSS

There are three ways of inserting a style sheet:

  • External CSS
  • Internal CSS
  • Inline CSS

External CSS

With an external style sheet, you can change the look of an entire website by changing just one file!

Each HTML page must include a reference to the external style sheet file inside the <link> element, inside the head section.

Example

External styles are defined within the <link> element, inside the <head> section of an HTML page:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

An external style sheet can be written in any text editor, and must be saved with a .css extension.

The external .css file should not contain any HTML tags.

Here is how the "mystyle.css" file looks:

"mystyle.css"

body {
  background-color: lightblue;
}

h1 {
  color: navy;
  margin-left: 20px;
}

Note: Do not add a space between the property value and the unit:
Incorrect (space): 
margin-left: 20 px;
Correct (nospace): 
margin-left: 20px;

Internal CSS

An internal style sheet may be used if one single HTML page has a unique style.

The internal style is defined inside the <style> element, inside the head section.

Example

Internal styles are defined within the <style> element, inside the <head> section of an HTML page:

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-color: linen;
}

h1 {
  color: maroon;
  margin-left: 40px;
}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

Inline CSS

An inline style may be used to apply a unique style for a single element.

To use inline styles, add the style attribute to the relevant element. The style attribute can contain any CSS property.

Example

Inline styles are defined within the "style" attribute of the relevant element:

<!DOCTYPE html>
<html>
<body>

<h1 style="color:blue;text-align:center;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>

</body>
</html>

Tip: An inline style loses many of the advantages of a style sheet (by mixing content with presentation). Use this method sparingly.

Multiple Style Sheets

If some properties have been defined for the same selector (element) in different style sheets, the value from the last read style sheet will be used. 

Assume that an external style sheet has the following style for the <h1> element:

h1 {
  color: navy;
}

Then, assume that an internal style sheet also has the following style for the <h1> element:

h1 {
  color: orange;   
}

Example

If the internal style is defined after the link to the external style sheet, the <h1> elements will be "orange":

<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<style>
h1 {
  color: orange;
}
</style>
</head>

Example

However, if the internal style is defined before the link to the external style sheet, the <h1> elements will be "navy": 

<head>
<style>
h1 {
  color: orange;
}
</style>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

Cascading Order

What style will be used when there is more than one style specified for an HTML element?

All the styles in a page will "cascade" into a new "virtual" style sheet by the following rules, where number one has the highest priority:

  1. Inline style (inside an HTML element)
  2. External and internal style sheets (in the head section)
  3. Browser default

So, an inline style has the highest priority, and will override external and internal styles and browser defaults.

Top of Form

CSS Comments

CSS comments are not displayed in the browser, but they can help document your source code.

CSS Comments

Comments are used to explain the code, and may help when you edit the source code at a later date.

Comments are ignored by browsers.

A CSS comment is placed inside the <style> element, and starts with /* and ends with */:

Example

/* This is a single-line comment */
{
  color: red;
}

You can add comments wherever you want in the code:

Example

{
  color: red;  /* Set text color to red */
}

Comments can also span multiple lines: 

Example

/* This is
a multi-line
comment */

{
  color: red;
}

HTML and CSS Comments

From the HTML tutorial, you learned that you can add comments to your HTML source by using the <!--...--> syntax.

In the following example, we use a combination of HTML and CSS comments:

Example

<!DOCTYPE html>
<html>
<head>
<style>
{
  color: red; /* Set text color to red */
}
</style>
</head>
<body>

<h2>My Heading</h2>

<!-- These paragraphs will be red -->
<p>Hello World!</p>
<p>This paragraph is styled with CSS.</p>
<p>CSS comments are not shown in the output.</p>

</body>
</html>

CSS Colors

Colors are specified using predefined color names, or RGB, HEX, HSL, RGBA, HSLA values.

CSS Color Names

In CSS, a color can be specified by using a predefined color name:

Tomato

Orange

DodgerBlue

MediumSeaGreen

Gray

SlateBlue

Violet


CSS Background Color

You can set the background color for HTML elements:

Hello World

 


Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Example

<h1 style="background-color:DodgerBlue;">Hello World</h1>
<p style="background-color:Tomato;">Lorem ipsum...</p>

CSS Text Color

You can set the color of text:

Hello World

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Example

<h1 style="color:Tomato;">Hello World</h1>
<p style="color:DodgerBlue;">Lorem ipsum...</p>
<p style="color:MediumSeaGreen;">Ut wisi enim...</p>

CSS Border Color

You can set the color of borders:

Hello World

Hello World

Hello World

Example

<h1 style="border:2px solid Tomato;">Hello World</h1>
<h1 style="border:2px solid DodgerBlue;">Hello World</h1>
<h1 style="border:2px solid Violet;">Hello World</h1>

CSS Color Values

In CSS, colors can also be specified using RGB values, HEX values, HSL values, RGBA values, and HSLA values:

Same as color name "Tomato":

rgb(255, 99, 71)

#ff6347

hsl(9, 100%, 64%)

Example

<h1 style="background-color:rgb(255, 99, 71);">...</h1>
<h1 style="background-color:#ff6347;">...</h1>
<h1 style="background-color:hsl(9, 100%, 64%);">...</h1>

<h1 style="background-color:rgba(255, 99, 71, 0.5);">...</h1>
<h1 style="background-color:hsla(9, 100%, 64%, 0.5);">...</h1>

CSS Backgrounds

The CSS background properties are used to add background effects for elements.

In these chapters, you will learn about the following CSS background properties:

  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position
  • background (shorthand property)

CSS background-color

The background-color property specifies the background color of an element.

Example

The background color of a page is set like this:

body {
  background-color: lightblue;
}

With CSS, a color is most often specified by:

  • a valid color name - like "red"
  • a HEX value - like "#ff0000"
  • an RGB value - like "rgb(255,0,0)"

Other Elements

You can set the background color for any HTML elements:

Example

Here, the <h1>, <p>, and <div> elements will have different background colors: 

h1 {
  background-color: green;
}

div {
  background-color: lightblue;
}

{
  background-color: yellow;
}

Opacity / Transparency

The opacity property specifies the opacity/transparency of an element. It can take a value from 0.0 - 1.0. The lower value, the more transparent:

opacity 1

opacity 0.6

opacity 0.3

opacity 0.1

Example

div {
  background-color: green;
  opacity: 0.3;
}

Note: When using the opacity property to add transparency to the background of an element, all of its child elements inherit the same transparency. This can make the text inside a fully transparent element hard to read.

Transparency using RGBA

If you do not want to apply opacity to child elements, like in our example above, use RGBA color values. The following example sets the opacity for the background color and not the text:

100% opacity

60% opacity

30% opacity

10% opacity

An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).

Example

div {
  background: rgba(0, 128, 0, 0.3) /* Green background with 30% opacity */
}

The CSS Background Color Property

Property

Description

background-color

Sets the background color of an element

 

CSS Borders

The CSS border properties allow you to specify the style, width, and color of an element's border.

I have borders on all sides.

I have a red bottom border.

I have rounded borders.

I have a blue left border.

CSS Border Style

The border-style property specifies what kind of border to display.

The following values are allowed:

  • dotted - Defines a dotted border
  • dashed - Defines a dashed border
  • solid - Defines a solid border
  • double - Defines a double border
  • groove - Defines a 3D grooved border. The effect depends on the border-color value
  • ridge - Defines a 3D ridged border. The effect depends on the border-color value
  • inset - Defines a 3D inset border. The effect depends on the border-color value
  • outset - Defines a 3D outset border. The effect depends on the border-color value
  • none - Defines no border
  • hidden - Defines a hidden border

The border-style property can have from one to four values (for the top border, right border, bottom border, and the left border).

Example

Demonstration of the different border styles:

p.dotted {border-style: dotted;}
p.dashed {border-style: dashed;}
p.solid {border-style: solid;}
p.double {border-style: double;}
p.groove {border-style: groove;}
p.ridge {border-style: ridge;}
p.inset {border-style: inset;}
p.outset {border-style: outset;}
p.none {border-style: none;}
p.hidden {border-style: hidden;}
p.mix {border-style: dotted dashed solid double;}

Result:

A dotted border.

A dashed border.

A solid border.

A double border.

A groove border. The effect depends on the border-color value.

A ridge border. The effect depends on the border-color value.

An inset border. The effect depends on the border-color value.

An outset border. The effect depends on the border-color value.

No border.

A hidden border.

A mixed border.

Note: None of the OTHER CSS border properties (which you will learn more about in the next chapters) will have ANY effect unless the border-style property is set!

CSS Margins

Margins are used to create space around elements, outside of any defined borders.

This element has a margin of 70px.

CSS Margins

The CSS margin properties are used to create space around elements, outside of any defined borders.

With CSS, you have full control over the margins. There are properties for setting the margin for each side of an element (top, right, bottom, and left).

Margin - Individual Sides

CSS has properties for specifying the margin for each side of an element:

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

All the margin properties can have the following values:

  • auto - the browser calculates the margin
  • length - specifies a margin in px, pt, cm, etc.
  • % - specifies a margin in % of the width of the containing element
  • inherit - specifies that the margin should be inherited from the parent element

Tip: Negative values are allowed.

Example

Set different margins for all four sides of a <p> element:

{
  margin-top: 100px;
  margin-bottom: 100px;
  margin-right: 150px;
  margin-left: 80px;
}

Margin - Shorthand Property

To shorten the code, it is possible to specify all the margin properties in one property.

The margin property is a shorthand property for the following individual margin properties:

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

So, here is how it works:

If the margin property has four values:

  • margin: 25px 50px 75px 100px;
    • top margin is 25px
    • right margin is 50px
    • bottom margin is 75px
    • left margin is 100px

Example

Use the margin shorthand property with four values:

{
  margin: 25px 50px 75px 100px;
}

If the margin property has three values:

  • margin: 25px 50px 75px;
    • top margin is 25px
    • right and left margins are 50px
    • bottom margin is 75px

Example

Use the margin shorthand property with three values: 

{
  margin: 25px 50px 75px;
}

If the margin property has two values:

  • margin: 25px 50px;
    • top and bottom margins are 25px
    • right and left margins are 50px

Example

Use the margin shorthand property with two values: 

{
  margin: 25px 50px;
}

If the margin property has one value:

  • margin: 25px;
    • all four margins are 25px

Example

Use the margin shorthand property with one value: 

{
  margin: 25px;
}

The auto Value

You can set the margin property to auto to horizontally center the element within its container.

The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.

Example

Use margin: auto:

div {
  width: 300px;
  margin: auto;
  border: 1px solid red;
}

The inherit Value

This example lets the left margin of the <p class="ex1"> element be inherited from the parent element (<div>):

Example

Use of the inherit value:

div {
  border: 1px solid red;
  margin-left: 100px;
}

p.ex1 {
  margin-left: inherit;
}

All CSS Margin Properties

Property

Description

margin

A shorthand property for setting all the margin properties in one declaration

margin-bottom

Sets the bottom margin of an element

margin-left

Sets the left margin of an element

margin-right

Sets the right margin of an element

margin-top

Sets the top margin of an element

CSS Margin Collapse

Sometimes two margins collapse into a single margin.

Margin Collapse

Top and bottom margins of elements are sometimes collapsed into a single margin that is equal to the largest of the two margins.

This does not happen on left and right margins! Only top and bottom margins!

Look at the following example:

Example

Demonstration of margin collapse:

h1 {
  margin: 0 0 50px 0;
}

h2 {
  margin: 20px 0 0 0;
}

In the example above, the <h1> element has a bottom margin of 50px and the <h2> element has a top margin set to 20px.

Common sense would seem to suggest that the vertical margin between the <h1> and the <h2> would be a total of 70px (50px + 20px). But due to margin collapse, the actual margin ends up being 50px.

Bottom of Form


All CSS Margin Properties

Property

Description

margin

A shorthand property for setting all the margin properties in one declaration

margin-bottom

Sets the bottom margin of an element

margin-left

Sets the left margin of an element

margin-right

Sets the right margin of an element

margin-top

Sets the top margin of an element

 

CSS Padding

Padding is used to create space around an element's content, inside of any defined borders.

This element has a padding of 70px.

CSS Padding

The CSS padding properties are used to generate space around an element's content, inside of any defined borders.

With CSS, you have full control over the padding. There are properties for setting the padding for each side of an element (top, right, bottom, and left).

Padding - Individual Sides

CSS has properties for specifying the padding for each side of an element:

  • padding-top
  • padding-right
  • padding-bottom
  • padding-left

All the padding properties can have the following values:

  • length - specifies a padding in px, pt, cm, etc.
  • % - specifies a padding in % of the width of the containing element
  • inherit - specifies that the padding should be inherited from the parent element

Note: Negative values are not allowed.

Example

Set different padding for all four sides of a <div> element:  

div {
  padding-top: 50px;
  padding-right: 30px;
  padding-bottom: 50px;
  padding-left: 80px;
}

Padding - Shorthand Property

To shorten the code, it is possible to specify all the padding properties in one property.

The padding property is a shorthand property for the following individual padding properties:

  • padding-top
  • padding-right
  • padding-bottom
  • padding-left

So, here is how it works:

If the padding property has four values:

  • padding: 25px 50px 75px 100px;
    • top padding is 25px
    • right padding is 50px
    • bottom padding is 75px
    • left padding is 100px

Example

Use the padding shorthand property with four values:

div {
  padding: 25px 50px 75px 100px;
}

If the padding property has three values:

  • padding: 25px 50px 75px;
    • top padding is 25px
    • right and left paddings are 50px
    • bottom padding is 75px

Example

Use the padding shorthand property with three values: 

div {
  padding: 25px 50px 75px;
}

If the padding property has two values:

  • padding: 25px 50px;
    • top and bottom paddings are 25px
    • right and left paddings are 50px

Example

Use the padding shorthand property with two values: 

div {
  padding: 25px 50px;
}

If the padding property has one value:

  • padding: 25px;
    • all four paddings are 25px

Example

Use the padding shorthand property with one value: 

div {
  padding: 25px;
}

Padding and Element Width

The CSS width property specifies the width of the element's content area. The content area is the portion inside the padding, border, and margin of an element.

So, if an element has a specified width, the padding added to that element will be added to the total width of the element. This is often an undesirable result.

Example

Here, the <div> element is given a width of 300px. However, the actual width of the <div> element will be 350px (300px + 25px of left padding + 25px of right padding):

div {
  width: 300px;
  padding: 25px;
}

To keep the width at 300px, no matter the amount of padding, you can use the box-sizing property. This causes the element to maintain its actual width; if you increase the padding, the available content space will decrease.

Example

Use the box-sizing property to keep the width at 300px, no matter the amount of padding:

div {
  width: 300px;
  padding: 25px;
  box-sizing: border-box;
}

Bottom of Form

All CSS Padding Properties

Property

Description

padding

A shorthand property for setting all the padding properties in one declaration

padding-bottom

Sets the bottom padding of an element

padding-left

Sets the left padding of an element

padding-right

Sets the right padding of an element

padding-top

Sets the top padding of an element

CSS Height, Width and Max-width

The CSS height and width properties are used to set the height and width of an element.

The CSS max-width property is used to set the maximum width of an element.

This element has a height of 50 pixels and a width of 100%.

CSS Setting height and width

The height and width properties are used to set the height and width of an element.

The height and width properties do not include padding, borders, or margins. It sets the height/width of the area inside the padding, border, and margin of the element.

CSS height and width Values

The height and width properties may have the following values:

  • auto - This is default. The browser calculates the height and width
  • length - Defines the height/width in px, cm, etc.
  • % - Defines the height/width in percent of the containing block
  • initial - Sets the height/width to its default value
  • inherit - The height/width will be inherited from its parent value

CSS height and width Examples

This element has a height of 200 pixels and a width of 50%

Example

Set the height and width of a <div> element:

div {
  height: 200px;
  width: 50%;
  background-color: powderblue;
}

This element has a height of 100 pixels and a width of 500 pixels.

Example

Set the height and width of another <div> element:

div {
  height: 100px;
  width: 500px;
  background-color: powderblue;
}

Note: Remember that the height and width properties do not include padding, borders, or margins! They set the height/width of the area inside the padding, border, and margin of the element!



Setting max-width

The max-width property is used to set the maximum width of an element.

The max-width can be specified in length values, like px, cm, etc., or in percent (%) of the containing block, or set to none (this is default. Means that there is no maximum width).

The problem with the <div> above occurs when the browser window is smaller than the width of the element (500px). The browser then adds a horizontal scrollbar to the page.

Using max-width instead, in this situation, will improve the browser's handling of small windows.

Tip: Drag the browser window to smaller than 500px wide, to see the difference between the two divs!

This element has a height of 100 pixels and a max-width of 500 pixels.

Note: If you for some reason use both the width property and the max-width property on the same element, and the value of the width property is larger than the max-width property; the max-width property will be used (and the width property will be ignored).

Example

This <div> element has a height of 100 pixels and a max-width of 500 pixels: 

div {
  max-width: 500px;
  height: 100px;
  background-color: powderblue;
}

All CSS Dimension Properties

Property

Description

height

Sets the height of an element

max-height

Sets the maximum height of an element

max-width

Sets the maximum width of an element

min-height

Sets the minimum height of an element

min-width

Sets the minimum width of an element

width

Sets the width of an element

CSS Box Model

All HTML elements can be considered as boxes.

The CSS Box Model

In CSS, the term "box model" is used when talking about design and layout.

The CSS box model is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content. The image below illustrates the box model:

Explanation of the different parts:

  • Content - The content of the box, where text and images appear
  • Padding - Clears an area around the content. The padding is transparent
  • Border - A border that goes around the padding and content
  • Margin - Clears an area outside the border. The margin is transparent

The box model allows us to add a border around elements, and to define space between elements. 

Example

Demonstration of the box model:

div {
  width: 300px;
  border: 15px solid green;
  padding: 50px;
  margin: 20px;
}

Width and Height of an Element

In order to set the width and height of an element correctly in all browsers, you need to know how the box model works.

Important: When you set 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 padding, borders and margins.

Example

This <div> element will have a total width of 350px: 

div {
  width: 320px;
  padding: 10px;
  border: 5px solid gray;
  margin: 0;
}

Here is the calculation:

320px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 0px (left + right margin)
= 350px

The total width of an element should be calculated like this:

Total element width = width + left padding + right padding + left border + right border + left margin + right margin

The total height of an element should be calculated like this:

Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin

Top of Form

 

CSS Outline

An outline is a line drawn outside the element's border.

This element has a black border and a green outline with a width of 10px.

CSS Outline

An outline is a line that is drawn around elements, OUTSIDE the borders, to make the element "stand out".

CSS has the following outline properties:

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

Note: Outline differs from borders! Unlike border, the outline is drawn outside the element's border, and may overlap other content. Also, the outline is NOT a part of the element's dimensions; the element's total width and height is not affected by the width of the outline.

CSS Outline Style

The outline-style property specifies the style of the outline, and can have one of the following values:

  • dotted - Defines a dotted outline
  • dashed - Defines a dashed outline
  • solid - Defines a solid outline
  • double - Defines a double outline
  • groove - Defines a 3D grooved outline
  • ridge - Defines a 3D ridged outline
  • inset - Defines a 3D inset outline
  • outset - Defines a 3D outset outline
  • none - Defines no outline
  • hidden - Defines a hidden outline

The following example shows the different outline-style values:

Example

Demonstration of the different outline styles:

p.dotted {outline-style: dotted;}
p.dashed {outline-style: dashed;}
p.solid {outline-style: solid;}
p.double {outline-style: double;}
p.groove {outline-style: groove;}
p.ridge {outline-style: ridge;}
p.inset {outline-style: inset;}
p.outset {outline-style: outset;}

Result:

A dotted outline.

A dashed outline.

A solid outline.

A double outline.

A groove outline. The effect depends on the outline-color value.

A ridge outline. The effect depends on the outline-color value.

An inset outline. The effect depends on the outline-color value.

An outset outline. The effect depends on the outline-color value.

Note: None of the other outline properties (which you will learn more about in the next chapters) will have ANY effect unless the outline-style property is set!

CSS Outline Width

The outline-width property specifies the width of the outline, and can have one of the following values:

  • thin (typically 1px)
  • medium (typically 3px)
  • thick (typically 5px)
  • A specific size (in px, pt, cm, em, etc)

The following example shows some outlines with different widths:

A thin outline.

A medium outline.

A thick outline.

A 4px thick outline.

Example

p.ex1 {
  border: 1px solid black;
  outline-style: solid;
  outline-color: red;
  outline-width: thin;
}

p.ex2 {
  border: 1px solid black;
  outline-style: solid;
  outline-color: red;
  outline-width: medium;
}

p.ex3 {
  border: 1px solid black;
  outline-style: solid;
  outline-color: red;
  outline-width: thick;
}

p.ex4 {
  border: 1px solid black;
  outline-style: solid;
  outline-color: red;
  outline-width: 4px;

CSS Outline Color

The outline-color property is used to set the color of the outline.

The color can be set by:

  • name - specify a color name, like "red"
  • HEX - specify a hex value, like "#ff0000"
  • RGB - specify a RGB value, like "rgb(255,0,0)"
  • HSL - specify a HSL value, like "hsl(0, 100%, 50%)"
  • invert - performs a color inversion (which ensures that the outline is visible, regardless of color background)

The following example shows some different outlines with different colors. Also notice that these elements also have a thin black border inside the outline:

A solid red outline.

A dotted blue outline.

An outset grey outline.

Example

p.ex1 {
  border: 2px solid black;
  outline-style: solid;
  outline-color: red;
}

p.ex2 {
  border: 2px solid black;
  outline-style: dotted;
  outline-color: blue;
}

p.ex3 {
  border: 2px solid black;
  outline-style: outset;
  outline-color: grey;
}

HEX Values

The outline color can also be specified using a hexadecimal value (HEX):

Example

p.ex1 {
  outline-style: solid;
  outline-color: #ff0000; /* red */
}

RGB Values

Or by using RGB values:

Example

p.ex1 {
  outline-style: solid;
  outline-color: rgb(255, 0, 0); /* red */
}

HSL Values

You can also use HSL values:

Example

p.ex1 {
  outline-style: solid;
  outline-color: hsl(0, 100%, 50%); /* red */
}

CSS Outline Shorthand

CSS Outline - Shorthand property

The outline property is a shorthand property for setting the following individual outline properties:

  • outline-width
  • outline-style (required)
  • outline-color

The outline property is specified as one, two, or three values from the list above. The order of the values does not matter.

The following example shows some outlines specified with the shorthand outline property:

A dashed outline.

A dotted red outline.

A 5px solid yellow outline.

A thick ridge pink outline.

Example

p.ex1 {outline: dashed;}
p.ex2 {outline: dotted red;}
p.ex3 {outline: 5px solid yellow;}
p.ex4 {outline: thick ridge pink;}

CSS Outline Offset

The outline-offset property adds space between an outline and the edge/border of an element. The space between an element and its outline is transparent.

The following example specifies an outline 15px outside the border edge:

This paragraph has an outline 15px outside the border edge.

Example

{
  margin: 30px;
  border: 1px solid black;
  outline: 1px solid red;
  outline-offset: 15px;
}

The following example shows that the space between an element and its outline is transparent:

This paragraph has an outline of 15px outside the border edge.

Example

{
  margin: 30px;
  background: yellow;
  border: 1px solid black;
  outline: 1px solid red;
  outline-offset: 15px;
}

Bottom of Form


All CSS Outline Properties

Property

Description

outline

A shorthand property for setting outline-width, outline-style, and outline-color in one declaration

outline-color

Sets the color of an outline

outline-offset

Specifies the space between an outline and the edge or border of an element

outline-style

Sets the style of an outline

outline-width

Sets the width of an outline

 

 

CSS Text

CSS has a lot of properties for formatting text.

TEXT FORMATTING

This text is styled with some of the text formatting properties. The heading uses the text-align, text-transform, and color properties. The paragraph is indented, aligned, and the space between characters is specified. The underline is removed from this colored.

Text Color

The color property is used to set the color of the text. The color is specified by:

  • a color name - like "red"
  • a HEX value - like "#ff0000"
  • an RGB value - like "rgb(255,0,0)"

The default text color for a page is defined in the body selector.

Example

body {
  color: blue;
}

h1 {
  color: green;
}

Text Color and Background Color

In this example, we define both the background-color property and the color property:

Example

body {
  background-color: lightgrey;
  color: blue;
}

h1 {
  background-color: black;
  color: white;
}

div {
  background-color: blue;
  color: white;
}

Important: High contrast is very important for people with vision problems. So, always ensure that the contrast between the text color and the background color (or background image) is good!

The CSS Text Color Property

Property

Description

color

Specifies the color of text

CSS Fonts

Choosing the right font for your website is important!

Font Selection is Important

Choosing the right font has a huge impact on how the readers experience a website.

The right font can create a strong identity for your brand.

Using a font that is easy to read is important. The font adds value to your text. It is also important to choose the correct color and text size for the font.


Generic Font Families

In CSS there are five generic font families:

  1. Serif fonts have a small stroke at the edges of each letter. They create a sense of formality and elegance.
  2. Sans-serif fonts have clean lines (no small strokes attached). They create a modern and minimalistic look.
  3. Monospace fonts - here all the letters have the same fixed width. They create a mechanical look. 
  4. Cursive fonts imitate human handwriting.
  5. Fantasy fonts are decorative/playful fonts.

All the different font names belong to one of the generic font families. 

Difference Between Serif and Sans-serif Fonts

Serif vs. Sans-serif

Note: On computer screens, sans-serif fonts are considered easier to read than serif fonts.

Some Font Examples

Generic Font Family

Examples of Font Names

Serif

Times New Roman
Georgia
Garamond

Sans-serif

Arial
Verdana
Helvetica

Monospace

Courier New
Lucida Console
Monaco

Cursive

Brush Script MT
Lucida Handwriting

Fantasy

Copperplate
Papyrus

The CSS font-family Property

In CSS, we use the font-family property to specify the font of a text.

Note: If the font name is more than one word, it must be in quotation marks, like: "Times New Roman".

Example

Specify some different fonts for three paragraphs:

.p1 {
  font-family: "Times New Roman", Times, serif;
}

.p2 {
  font-family: Arial, Helvetica, sans-serif;
}

.p3 {
  font-family: "Lucida Console", "Courier New", monospace;

CSS Web Safe Fonts

What are Web Safe Fonts?

Web safe fonts are fonts that are universally installed across all browsers and devices.

Fallback Fonts

However, there are no 100% completely web safe fonts. There is always a chance that a font is not found or is not installed properly.

Therefore, it is very important to always use fallback fonts.

This means that you should add a list of similar "backup fonts" in the font-family property. If the first font does not work, the browser will try the next one, and the next one, and so on. Always end the list with a generic font family name.

Example

Here, there are three font types: Tahoma, Verdana, and sans-serif. The second and third fonts are backups, in case the first one is not found.

{
font-family: Tahoma, Verdana, sans-serif;
}

Best Web Safe Fonts for HTML and CSS

The following list are the best web safe fonts for HTML and CSS:

  • Arial (sans-serif)
  • Verdana (sans-serif)
  • Tahoma (sans-serif)
  • Trebuchet MS (sans-serif)
  • Times New Roman (serif)
  • Georgia (serif)
  • Garamond (serif)
  • Courier New (monospace)
  • Brush Script MT (cursive)

CSS Font Fallbacks

Commonly Used Font Fallbacks

Below are some commonly used font fallbacks, organized by the 5 generic font families:

  • Serif
  • Sans-serif
  • Monospace
  • Cursive
  • Fantasy

Serif Fonts

font-family

Example text

"Times New Roman", Times, serif

This is a Heading

This is a paragraph.

Georgia, serif

This is a Heading

This is a paragraph.

Garamond, serif

This is a Heading

This is a paragraph.

Sans-Serif Fonts

font-family

Example text

Arial, Helvetica, sans-serif

This is a Heading

This is a paragraph.

Tahoma, Verdana, sans-serif

This is a Heading

This is a paragraph.

"Trebuchet MS", Helvetica, sans-serif

This is a Heading

This is a paragraph.

Geneva, Verdana, sans-serif

This is a Heading

This is a paragraph.


Monospace Fonts

font-family

Example text

"Courier New", Courier, monospace

This is a Heading

This is a paragraph.

Cursive Fonts

font-family

Example text

"Brush Script MT", cursive

This is a Heading

This is a paragraph.

Fantasy Fonts

font-family

Example text

Copperplate, Papyrus, fantasy

This is a Heading

This is a paragraph.

Bottom of Form

All CSS Font Properties

Property

Description

font

Sets all the font properties in one declaration

font-family

Specifies the font family for text

font-size

Specifies the font size of text

font-style

Specifies the font style for text

font-variant

Specifies whether or not a text should be displayed in a small-caps font

font-weight

Specifies the weight of a font

 

 

 

 

CSS Icons

Icons can easily be added to your HTML page, by using an icon library.

How To Add Icons

The simplest way to add an icon to your HTML page, is with an icon library, such as Font Awesome.

Add the name of the specified icon class to any inline HTML element (like <i> or <span>).

All the icons in the icon libraries below, are scalable vectors that can be customized with CSS (size, color, shadow, etc.)


Font Awesome Icons

To use the Font Awesome icons, go to fontawesome.com, sign in, and get a code to add in the <head> section of your HTML page:

<script src="https://kit.fontawesome.com/yourcode.js" crossorigin="anonymous"></script>

Note: No downloading or installation is required!

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script>
</head>
<body>

<i class="fas fa-cloud"></i>
<i class="fas fa-heart"></i>
<i class="fas fa-car"></i>
<i class="fas fa-file"></i>
<i class="fas fa-bars"></i>

</body>
</html>

 

 

CSS Links

With CSS, links can be styled in many different ways.

Text Link Text Link Link Button Link Button

Styling Links

Links can be styled with any CSS property (e.g. colorfont-familybackground, etc.).

Example

{
  color: hotpink;
}

In addition, links can be styled differently depending on what state they are in.

The four links states are:

  • a:link - a normal, unvisited link
  • a:visited - a link the user has visited
  • a:hover - a link when the user mouses over it
  • a:active - a link the moment it is clicked

Example

/* unvisited link */
a:link {
  color: red;
}

/* visited link */
a:visited {
  color: green;
}

/* mouse over link */
a:hover {
  color: hotpink;
}

/* selected link */
a:active {
  color: blue;
}

When setting the style for several link states, there are some order rules:

  • a:hover MUST come after a:link and a:visited
  • a:active MUST come after a:hover

Text Decoration

The text-decoration property is mostly used to remove underlines from links:

Example

a:link {
  text-decoration: none;
}

a:visited {
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

a:active {
  text-decoration: underline;
}

Background Color

The background-color property can be used to specify a background color for links:

Example

a:link {
  background-color: yellow;
}

a:visited {
  background-color: cyan;
}

a:hover {
  background-color: lightgreen;
}

a:active {
  background-color: hotpink;
} 

Link Buttons

This example demonstrates a more advanced example where we combine several CSS properties to display links as boxes/buttons:

Example

a:link, a:visited {
  background-color: #f44336;
  color: white;
  padding: 14px 25px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
}

a:hover, a:active {
  background-color: red;
}

More Examples

Example

This example demonstrates how to add other styles to hyperlinks:

a.one:link {color: #ff0000;}
a.one:visited {color: #0000ff;}
a.one:hover {color: #ffcc00;}

a.two:link {color: #ff0000;}
a.two:visited {color: #0000ff;}
a.two:hover {font-size: 150%;}

a.three:link {color: #ff0000;}
a.three:visited {color: #0000ff;}
a.three:hover {background: #66ff66;}

a.four:link {color: #ff0000;}
a.four:visited {color: #0000ff;}
a.four:hover {font-family: monospace;}

a.five:link {color: #ff0000; text-decoration: none;}
a.five:visited {color: #0000ff; text-decoration: none;}
a.five:hover {text-decoration: underline;}

Example

Another example of how to create link boxes/buttons:

a:link, a:visited {
  background-color: white;
  color: black;
  border: 2px solid green;
  padding: 10px 20px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
}

a:hover, a:active {
  background-color: green;
  color: white;
}

This example demonstrates the different types of cursors (can be useful for links):

<span style="cursor: auto">auto</span><br>
<span style="cursor: crosshair">crosshair</span><br>
<span style="cursor: default">default</span><br>
<span style="cursor: e-resize">e-resize</span><br>
<span style="cursor: help">help</span><br>
<span style="cursor: move">move</span><br>
<span style="cursor: n-resize">n-resize</span><br>
<span style="cursor: ne-resize">ne-resize</span><br>
<span style="cursor: nw-resize">nw-resize</span><br>
<span style="cursor: pointer">pointer</span><br>
<span style="cursor: progress">progress</span><br>
<span style="cursor: s-resize">s-resize</span><br>
<span style="cursor: se-resize">se-resize</span><br>
<span style="cursor: sw-resize">sw-resize</span><br>
<span style="cursor: text">text</span><br>
<span style="cursor: w-resize">w-resize</span><br>
<span style="cursor: wait">wait</span>

CSS Lists

❮ PreviousNext ❯

Unordered Lists:

  • Coffee
  • Tea
  • Coca Cola
  • Coffee
  • Tea
  • Coca Cola

Ordered Lists:

  1. Coffee
  2. Tea
  3. Coca Cola
  1. Coffee
  2. Tea
  3. Coca Cola

HTML Lists and CSS List Properties

In HTML, there are two main types of lists:

  • unordered lists (<ul>) - the list items are marked with bullets
  • ordered lists (<ol>) - the list items are marked with numbers or letters

The CSS list properties allow you to:

  • Set different list item markers for ordered lists
  • Set different list item markers for unordered lists
  • Set an image as the list item marker
  • Add background colors to lists and list items

Different List Item Markers

The list-style-type property specifies the type of list item marker.

The following example shows some of the available list item markers:

Example

ul.a {
  list-style-type: circle;
}

ul.b {
  list-style-type: square;
}

ol.c {
  list-style-type: upper-roman;
}

ol.d {
  list-style-type: lower-alpha;
}

Note: Some of the values are for unordered lists, and some for ordered lists.

An Image as The List Item Marker

The list-style-image property specifies an image as the list item marker:

Example

ul {
  list-style-image: url('sqpurple.gif');
}

Position The List Item Markers

The list-style-position property specifies the position of the list-item markers (bullet points).

"list-style-position: outside;" means that the bullet points will be outside the list item. The start of each line of a list item will be aligned vertically. This is default:

  • Coffee - A brewed drink prepared from roasted coffee beans...
  • Tea
  • Coca-cola

"list-style-position: inside;" means that the bullet points will be inside the list item. As it is part of the list item, it will be part of the text and push the text at the start:

  • Coffee - A brewed drink prepared from roasted coffee beans...
  • Tea
  • Coca-cola

Example

ul.a {
  list-style-position: outside;
}

ul.b {
  list-style-position: inside;
}

Remove Default Settings

The list-style-type:none property can also be used to remove the markers/bullets. Note that the list also has default margin and padding. To remove this, add margin:0 and padding:0 to <ul> or <ol>:

Example

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

List - Shorthand property

The list-style property is a shorthand property. It is used to set all the list properties in one declaration:

Example

ul {
  list-style: square inside url("sqpurple.gif");
}

When using the shorthand property, the order of the property values are:

  • list-style-type (if a list-style-image is specified, the value of this property will be displayed if the image for some reason cannot be displayed)
  • list-style-position (specifies whether the list-item markers should appear inside or outside the content flow)
  • list-style-image (specifies an image as the list item marker)

If one of the property values above is missing, the default value for the missing property will be inserted, if any.

Styling List With Colors

We can also style lists with colors, to make them look a little more interesting.

Anything added to the <ol> or <ul> tag, affects the entire list, while properties added to the <li> tag will affect the individual list items:

Example

ol {
  background: #ff9999;
  padding: 20px;
}

ul {
  background: #3399ff;
  padding: 20px;
}

ol li {
  background: #ffe5e5;
  color: darkred;
  padding: 5px;
  margin-left: 35px;
}

ul li {
  background: #cce5ff;
  color: darkblue;
  margin: 5px;
}

Result:

1.   Coffee

2.   Tea

3.   Coca Cola

·         Coffee

·         Tea

·         Coca Cola

 

Bottom of Form

All CSS List Properties

Property

Description

list-style

Sets all the properties for a list in one declaration

list-style-image

Specifies an image as the list-item marker

list-style-position

Specifies the position of the list-item markers (bullet points)

list-style-type

Specifies the type of list-item marker

CSS Tables

Table Borders

To specify table borders in CSS, use the border property.

The example below specifies a solid border for <table>, <th>, and <td> elements:

Firstname

Lastname

Name

Name

Example

table, th, td {
  border: 1px solid;
}

Full-Width Table

The table above might seem small in some cases. If you need a table that should span the entire screen (full-width), add width: 100% to the <table> element:

Firstname

Lastname

Example

table {
  width: 100%;
}

Double Borders

Notice that the table in the examples above have double borders. This is because both the table and the <th> and <td> elements have separate borders.

To remove double borders, take a look at the example below.

Collapse Table Borders

The border-collapse property sets whether the table borders should be collapsed into a single border:

Firstname

Lastname

Example

table {
  border-collapse: collapse;
}

If you only want a border around the table, only specify the border property for <table>:

Firstname

Lastname

Example

table {
  border: 1px solid;
}

CSS Table Size

Table Width and Height

The width and height of a table are defined by the width and height properties.

The example below sets the width of the table to 100%, and the height of the <th> elements to 70px:

Firstname

Lastname

Savings

Example

table {
  width: 100%;
}

th {
  height: 70px;
}

To create a table that should only span half the page, use width: 50%:

Firstname

Lastname

Savings

Name

Name

Name

Example

table {
  width: 50%;
}

CSS Table Alignment

Horizontal Alignment

The text-align property sets the horizontal alignment (like left, right, or center) of the content in <th> or <td>.

By default, the content of <th> elements are center-aligned and the content of <td> elements are left-aligned.

To center-align the content of  <td> elements as well, use text-align: center:

Firstname

Lastname

Savings

Name

Name

Name

Example

td {
  text-align: center;
}

To left-align the content, force the alignment of <th> elements to be left-aligned, with the text-align: left property:

Firstname

Lastname

Savings

Name

Name

Name

Example

th {
  text-align: left;
}

Vertical Alignment

The vertical-align property sets the vertical alignment (like top, bottom, or middle) of the content in <th> or <td>.

By default, the vertical alignment of the content in a table is middle (for both <th> and <td> elements).

The following example sets the vertical text alignment to bottom for <td> elements:

Firstname

Lastname

Savings

Name

Name

Name

Example

td {
  height: 50px;
  vertical-align: bottom;
}

CSS Table Alignment

Horizontal Alignment

The text-align property sets the horizontal alignment (like left, right, or center) of the content in <th> or <td>.

By default, the content of <th> elements are center-aligned and the content of <td> elements are left-aligned.

To center-align the content of  <td> elements as well, use text-align: center:

Firstname

Lastname

Savings

Name

Name

Name

Example

td {
  text-align: center;
}

To left-align the content, force the alignment of <th> elements to be left-aligned, with the text-align: left property:

Firstname

Lastname

Savings

Name

Name

Name

Example

th {
  text-align: left;
}

Vertical Alignment

The vertical-align property sets the vertical alignment (like top, bottom, or middle) of the content in <th> or <td>.

By default, the vertical alignment of the content in a table is middle (for both <th> and <td> elements).

The following example sets the vertical text alignment to bottom for <td> elements:

Firstname

Lastname

Savings

Name

Name

Name

Example

td {
  height: 50px;
  vertical-align: bottom;
}

CSS Responsive Table

Responsive Table

A responsive table will display a horizontal scroll bar if the screen is too small to display the full content:

 

First Name

Last Name

Points

Points

Points

Points

Points

Points

Points

Points

Points

Name

Name

00

00

00

00

00

00

00

00

00

Name

Name

00

00

00

00

00

00

00

00

00

Name

Name

00

00

00

00

00

00

00

00

00

Add a container element (like <div>) with overflow-x:auto around the <table> element to make it responsive:

Example

<div style="overflow-x:auto;">

<table>
... table content ...
</table>

</div>

Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown when being used (even though "overflow:scroll" is set).

Bottom of Form


CSS Table Properties

Property

Description

border

Sets all the border properties in one declaration

border-collapse

Specifies whether or not table borders should be collapsed

border-spacing

Specifies the distance between the borders of adjacent cells

caption-side

Specifies the placement of a table caption

empty-cells

Specifies whether or not to display borders and background on empty cells in a table

table-layout

Sets the layout algorithm to be used for a table

 

CSS Layout - The display Property

The display property is the most important CSS property for controlling layout.

The display Property

The display property specifies if/how an element is displayed.

Every HTML element has a default display value depending on what type of element it is. The default display value for most elements is block or inline.

Click to show panel

Block-level Elements

A block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).

The <div> element is a block-level element.

Examples of block-level elements:

  • <div>
  • <h1> - <h6>
  • <p>
  • <form>
  • <header>
  • <footer>
  • <section>

Inline Elements

An inline element does not start on a new line and only takes up as much width as necessary.

This is an inline <span> element inside a paragraph.

Examples of inline elements:

  • <span>
  • <a>
  • <img>

Display: none;

display: none; is commonly used with JavaScript to hide and show elements without deleting and recreating them. Take a look at our last example on this page if you want to know how this can be achieved.

The <script> element uses display: none; as default. 

Override The Default Display Value

As mentioned, every element has a default display value. However, you can override this.

Changing an inline element to a block element, or vice versa, can be useful for making the page look a specific way, and still follow the web standards.

A common example is making inline <li> elements for horizontal menus:

Example

li {
  display: inline;
}

Note: Setting the display property of an element only changes how the element is displayed, NOT what kind of element it is. So, an inline element with display: block; is not allowed to have other block elements inside it.

The following example displays <span> elements as block elements:

Example

span {
  display: block;
}

The following example displays <a> elements as block elements:

Example

{
  display: block;
}

Hide an Element - display:none or visibility:hidden?

display:none

Italy

Remove

visibility:hidden

Forest

Hide

Reset

Lights

Reset All

Hiding an element can be done by setting the display property to none. The element will be hidden, and the page will be displayed as if the element is not there:

Example

h1.hidden {
  display: none;
}

visibility:hidden; also hides an element.

However, the element will still take up the same space as before. The element will be hidden, but still affect the layout:

Example

h1.hidden {
  visibility: hidden;
}

Bottom of Form


CSS Display/Visibility Properties

Property

Description

display

Specifies how an element should be displayed

visibility

Specifies whether or not an element should be visible

CSS Layout - width and max-width

❮ PreviousNext ❯

Using width, max-width and margin: auto;

As mentioned in the previous chapter; a block-level element always takes up the full width available (stretches out to the left and right as far as it can).

Setting the width of a block-level element will prevent it from stretching out to the edges of its container. Then, you can set the margins to auto, to horizontally center the element within its container. The element will take up the specified width, and the remaining space will be split equally between the two margins:

This <div> element has a width of 500px, and margin set to auto.



Note: The problem with the <div> above occurs when the browser window is smaller than the width of the element. The browser then adds a horizontal scrollbar to the page.

Using max-width instead, in this situation, will improve the browser's handling of small windows. This is important when making a site usable on small devices:

This <div> element has a max-width of 500px, and margin set to auto.


Tip: Resize the browser window to less than 500px wide, to see the difference between the two divs!

Here is an example of the two divs above:

Example

div.ex1 {
  width: 500px;
  margin: auto;
  border: 3px solid #73AD21;
}

div.ex2 {
  max-width: 500px;
  margin: auto;
  border: 3px solid #73AD21;
}

CSS Layout - The position Property

❮ PreviousNext ❯


The position property specifies the type of positioning method used for an element (static, relative, fixed, absolute or sticky).


The position Property

The position property specifies the type of positioning method used for an element.

There are five different position values:

  • static
  • relative
  • fixed
  • absolute
  • sticky

Elements are then positioned using the top, bottom, left, and right properties. However, these properties will not work unless the position property is set first. They also work differently depending on the position value.


position: static;

HTML elements are positioned static by default.

Static positioned elements are not affected by the top, bottom, left, and right properties.

An element with position: static; is not positioned in any special way; it is always positioned according to the normal flow of the page:

This <div> element has position: static;

Here is the CSS that is used:

Example

div.static {
  position: static;
  border: 3px solid #73AD21;
}

position: relative;

An element with position: relative; is positioned relative to its normal position.

Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element.

This <div> element has position: relative;

Here is the CSS that is used:

Example

div.relative {
  position: relative;
  left: 30px;
  border: 3px solid #73AD21;
}


position: fixed;

An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element.

A fixed element does not leave a gap in the page where it would normally have been located.

Notice the fixed element in the lower-right corner of the page. Here is the CSS that is used:

Example

div.fixed {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 300px;
  border: 3px solid #73AD21;
}

This <div> element has position: fixed;

position: absolute;

An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).

However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.

Here is a simple example:

This <div> element has position: relative;

This <div> element has position: absolute;

Here is the CSS that is used:

Example

div.relative {
  position: relative;
  width: 400px;
  height: 200px;
  border: 3px solid #73AD21;
}

div.absolute {
  position: absolute;
  top: 80px;
  right: 0;
  width: 200px;
  height: 100px;
  border: 3px solid #73AD21;
}

position: sticky;

An element with position: sticky; is positioned based on the user's scroll position.

A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).

Note: Internet Explorer does not support sticky positioning. Safari requires a -webkit- prefix (see example below). You must also specify at least one of toprightbottom or left for sticky positioning to work.

In this example, the sticky element sticks to the top of the page (top: 0), when you reach its scroll position.

Example

div.sticky {
  position: -webkit-sticky; /* Safari */
  position: sticky;
  top: 0;
  background-color: green;
  border: 2px solid #4CAF50;
}

Positioning Text In an Image

How to position text over an image:

Example

Cinque Terre

Bottom Left

Top Left

Top Right

Bottom Right

Centered

 

All CSS Positioning Properties

Property

Description

bottom

Sets the bottom margin edge for a positioned box

clip

Clips an absolutely positioned element

left

Sets the left margin edge for a positioned box

position

Specifies the type of positioning for an element

right

Sets the right margin edge for a positioned box

top

Sets the top margin edge for a positioned box

 

CSS Layout - The z-index Property

The z-index property specifies the stack order of an element.

The z-index Property

When elements are positioned, they can overlap other elements.

The z-index property specifies the stack order of an element (which element should be placed in front of, or behind, the others).

An element can have a positive or negative stack order:

This is a heading

https://www.w3schools.com/css/img_tree.png

Because the image has a z-index of -1, it will be placed behind the text.

Example

img {
  position: absolute;
  left: 0px;
  top: 0px;
  z-index: -1;
}

Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display: flex elements).

Another z-index Example

Example

Here we see that an element with greater stack order is always above an element with a lower stack order:

<html>
<head>
<style>
.container {
  position: relative;
}

.black-box {
  position: relative;
  z-index: 1;
  border: 2px solid black;
  height: 100px;
  margin: 30px;
}

.gray-box {
  position: absolute;
  z-index: 3;
  background: lightgray;
  height: 60px;
  width: 70%;
  left: 50px;
  top: 50px;
}

.green-box {
  position: absolute;
  z-index: 2;
  background: lightgreen;
  width: 35%;
  left: 270px;
  top: -15px;
  height: 100px;
}
</style>
</head>
<body>

<div class="container">
  
<div class="black-box">Black box</div>
  
<div class="gray-box">Gray box</div>
  
<div class="green-box">Green box</div>
</div>

</body>
</html>

Without z-index

If two positioned elements overlap each other without a z-index specified, the element defined last in the HTML code will be shown on top.

Example

Same example as above, but here with no z-index specified:

<html>
<head>
<style>
.container {
  position: relative;
}

.black-box {
  position: relative;
  border: 2px solid black;
  height: 100px;
  margin: 30px;
}

.gray-box {
  position: absolute;
  background: lightgray;
  height: 60px;
  width: 70%;
  left: 50px;
  top: 50px;
}

.green-box {
  position: absolute;
  background: lightgreen;
  width: 35%;
  left: 270px;
  top: -15px;
  height: 100px;
}
</style>
</head>
<body>

<div class="container">
  
<div class="black-box">Black box</div>
  
<div class="gray-box">Gray box</div>
  
<div class="green-box">Green box</div>
</div>

</body>
</html>

Top of Form

Bottom of Form

 CSS Property

Property

Description

z-index

Sets the stack order of an element

CSS Layout - float and clear

The CSS float property specifies how an element should float.

The CSS clear property specifies what elements can float beside the cleared element and on which side.

The float Property

The float property is used for positioning and formatting content e.g. let an image float left to the text in a container.

The float property can have one of the following values:

  • left - The element floats to the left of its container
  • right - The element floats to the right of its container
  • none - The element does not float (will be displayed just where it occurs in the text). This is default
  • inherit - The element inherits the float value of its parent

In its simplest use, the float property can be used to wrap text around images.

Example - float: right;

The following example specifies that an image should float to the right in a text:

PineappleLorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac...

Example

img {
  float: right;
}

Example - float: left;

The following example specifies that an image should float to the left in a text:

PineappleLorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac...

Example

img {
  float: left;
}

Example - No float

In the following example the image will be displayed just where it occurs in the text (float: none;):

Pineapple Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac...

Example

img {
  float: none;
}

Example - Float Next To Each Other

Normally div elements will be displayed on top of each other. However, if we use float: left we can let elements float next to each other:

Example

div {
  float: left;
  padding: 15px;
}

.div1 {
  background: red;
}

.div2 {
  background: yellow;
}

.div3 {
  background: green;
}

CSS Layout - display: inline-block

The display: inline-block Value

Compared to display: inline, the major difference is that display: inline-block allows to set a width and height on the element.

Also, with display: inline-block, the top and bottom margins/paddings are respected, but with display: inline they are not.

Compared to display: block, the major difference is that display: inline-block does not add a line-break after the element, so the element can sit next to other elements.

The following example shows the different behavior of display: inlinedisplay: inline-block and display: block:

Example

span.a {
  display: inline; /* the default for span */
  width: 100px;
  height: 100px;
  padding: 5px;
  border: 1px solid blue;
  background-color: yellow;
}

span.b {
  display: inline-block;
  width: 100px;
  height: 100px;
  padding: 5px;
  border: 1px solid blue;
  background-color: yellow;
}

span.c {
  display: block;
  width: 100px;
  height: 100px;
  padding: 5px;
  border: 1px solid blue;
  background-color: yellow;
}

Using inline-block to Create Navigation Links

One common use for display: inline-block is to display list items horizontally instead of vertically. The following example creates horizontal navigation links:

Example

.nav {
  background-color: yellow;
  list-style-type: none;
  text-align: center; 
  padding: 0;
  margin: 0;
}

.nav li {
  display: inline-block;
  font-size: 20px;
  padding: 20px;
}

CSS Layout - Horizontal & Vertical Align

❮ PreviousNext ❯

 

▲▼

Center elements
horizontally and vertically

Center Align Elements

To horizontally center a block element (like <div>), use margin: auto;

Setting the width of the element will prevent it from stretching out to the edges of its container.

The element will then take up the specified width, and the remaining space will be split equally between the two margins:

This div element is centered.

Example

.center {
  margin: auto;
  width: 50%;
  border: 3px solid green;
  padding: 10px;
}

Note: Center aligning has no effect if the width property is not set (or set to 100%).

Center Align Text

To just center the text inside an element, use text-align: center;

This text is centered.

Example

.center {
  text-align: center;
  border: 3px solid green;
}

 

Center an Image

To center an image, set left and right margin to auto and make it into a block element:

Paris

Example

img {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 40%;
}

Left and Right Align - Using position

One method for aligning elements is to use position: absolute;:

In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.

Example

.right {
  position: absolute;
  right: 0px;
  width: 300px;
  border: 3px solid #73AD21;
  padding: 10px;
}

Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.


Left and Right Align - Using float

Another method for aligning elements is to use the float property:

Example

.right {
  float: right;
  width: 300px;
  border: 3px solid #73AD21;
  padding: 10px;
}

The clearfix Hack

Note: If an element is taller than the element containing it, and it is floated, it will overflow outside of its container. You can use the "clearfix hack" to fix this (see example below).

Without Clearfix

https://www.w3schools.com/howto/clearfix_prob.jpg

With Clearfix

https://www.w3schools.com/howto/clearfix_solution.jpg

Then we can add the clearfix hack to the containing element to fix this problem:

Example

.clearfix::after {
  content: "";
  clear: both;
  display: table;
}

Center Vertically - Using padding

There are many ways to center an element vertically in CSS. A simple solution is to use top and bottom padding:

I am vertically centered.

Example

.center {
  padding: 70px 0;
  border: 3px solid green;
}

To center both vertically and horizontally, use padding and text-align: center:

I am vertically and horizontally centered.

Example

.center {
  padding: 70px 0;
  border: 3px solid green;
  text-align: center;
}

Center Vertically - Using line-height

Another trick is to use the line-height property with a value that is equal to the height property:

I am vertically and horizontally centered.

Example

.center {
  line-height: 200px;
  height: 200px;
  border: 3px solid green;
  text-align: center;
}

/* If the text has multiple lines, add the following: */
.center p {
  line-height: 1.5;
  display: inline-block;
  vertical-align: middle;
}

Center Vertically - Using position & transform

If padding and line-height are not options, another solution is to use positioning and the transform property:

I am vertically and horizontally centered.

Example

.center {
  height: 200px;
  position: relative;
  border: 3px solid green;
}

.center p {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Center Vertically - Using Flexbox

You can also use flexbox to center things. Just note that flexbox is not supported in IE10 and earlier versions:

I am vertically and horizontally centered.

Example

.center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  border: 3px solid green;
}

Top of Form

CSS Combinators

❮ PreviousNext ❯

A combinator is something that explains the relationship between the selectors.

A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.

There are four different combinators in CSS:

  • descendant selector (space)
  • child selector (>)
  • adjacent sibling selector (+)
  • general sibling selector (~)

Descendant Selector

The descendant selector matches all elements that are descendants of a specified element.

The following example selects all <p> elements inside <div> elements: 

Example

div p {
  background-color: yellow;
}

Child Selector (>)

The child selector selects all elements that are the children of a specified element.

The following example selects all <p> elements that are children of a <div> element:

Example

div > p {
  background-color: yellow;
}

Adjacent Sibling Selector (+)

The adjacent sibling selector is used to select an element that is directly after another specific element.

Sibling elements must have the same parent element, and "adjacent" means "immediately following".

The following example selects the first <p> element that are placed immediately after <div> elements:

Example

div + p {
  background-color: yellow;
}

General Sibling Selector (~)

The general sibling selector selects all elements that are next siblings of a specified element.

The following example selects all <p> elements that are next siblings of <div> elements: 

Example

div ~ p {
  background-color: yellow;
}

All CSS Combinator Selectors

Selector

Example

Example description

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 the first <p> element that are placed immediately after <div> elements

element1~element2

p ~ ul

Selects every <ul> element that are preceded by a <p> element

❮ PreviousNext ❯

CSS Pseudo-elements

What are Pseudo-Elements?

A CSS pseudo-element is used to style specified parts of an element.

For example, it can be used to:

  • Style the first letter, or line, of an element
  • Insert content before, or after, the content of an element

Syntax

The syntax of pseudo-elements:

selector::pseudo-element {
  property: value;
}

The ::first-line Pseudo-element

The ::first-line pseudo-element is used to add a special style to the first line of a text.

The following example formats the first line of the text in all <p> elements:

Example 

p::first-line {
  color: #ff0000;
  font-variant: small-caps;
}

Note: The ::first-line pseudo-element can only be applied to block-level elements.

The following properties apply to the ::first-line pseudo-element:

  • font properties
  • color properties
  • background properties
  • word-spacing
  • letter-spacing
  • text-decoration
  • vertical-align
  • text-transform
  • line-height
  • clear

Notice the double colon notation - ::first-line versus :first-line

The double colon replaced the single-colon notation for pseudo-elements in CSS3. This was an attempt from W3C to distinguish between 
pseudo-classes and pseudo-elements.

The single-colon syntax was used for both pseudo-classes and pseudo-elements in CSS2 and CSS1.

For backward compatibility, the single-colon syntax is acceptable for CSS2 and CSS1 pseudo-elements.

The ::first-letter Pseudo-element

The ::first-letter pseudo-element is used to add a special style to the first letter of a text.

The following example formats the first letter of the text in all <p> elements: 

Example

p::first-letter {
  color: #ff0000;
  font-size: xx-large;
}

Note: The ::first-letter pseudo-element can only be applied to block-level elements.

The following properties apply to the ::first-letter pseudo- element: 

  • font properties
  • color properties 
  • background properties
  • margin properties
  • padding properties
  • border properties
  • text-decoration
  • vertical-align (only if "float" is "none")
  • text-transform
  • line-height
  • float
  • clear

Pseudo-elements and HTML Classes

Pseudo-elements can be combined with HTML classes: 

Example

p.intro::first-letter {
  color: #ff0000;
  font-size: 200%;
}

The example above will display the first letter of paragraphs with class="intro", in red and in a larger size.

Multiple Pseudo-elements

Several pseudo-elements can also be combined.

In the following example, the first letter of a paragraph will be red, in an xx-large font size. The rest of the first line will be blue, and in small-caps. The rest of the paragraph will be the default font size and color:

Example

p::first-letter {
  color: #ff0000;
  font-size: xx-large;
}

p::first-line {
  color: #0000ff;
  font-variant: small-caps;
}

CSS - The ::before Pseudo-element

The ::before pseudo-element can be used to insert some content before the content of an element.

The following example inserts an image before the content of each <h1> element:

Example

h1::before {
  content: url(smiley.gif);
}

CSS - The ::after Pseudo-element

The ::after pseudo-element can be used to insert some content after the content of an element.

The following example inserts an image after the content of each <h1> element:

Example

h1::after {
  content: url(smiley.gif);
}

CSS - The ::marker Pseudo-element

The ::marker pseudo-element selects the markers of list items.

The following example styles the markers of list items:

Example

::marker {
  color: red;
  font-size: 23px;
}

CSS - The ::selection Pseudo-element

The ::selection pseudo-element matches the portion of an element that is selected by a user.

The following CSS properties can be applied to ::selectioncolorbackgroundcursor, and outline.

The following example makes the selected text red on a yellow background:

Example

::selection {
  color: red;
  background: yellow;
}

Bottom of Form


All CSS Pseudo Elements

Selector

Example

Example description

::after

p::after

Insert something after the content of each <p> element

::before

p::before

Insert something before the content of each <p> element

::first-letter

p::first-letter

Selects the first letter of each <p> element

::first-line

p::first-line

Selects the first line of each <p> element

::marker

::marker

Selects the markers of list items

::selection

p::selection

Selects the portion of an element that is selected by a user

All CSS Pseudo Classes

Selector

Example

Example description

:active

a:active

Selects the active link

: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

:enabled

input:enabled

Selects every enabled <input> element

:first-child

p:first-child

Selects every <p> elements that is the first child of its parent

: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 that 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 value starting with "it"

:last-child

p:last-child

Selects every <p> elements 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 a "readonly" attribute specified

:read-write

input:read-write

Selects <input> elements with no "readonly" attribute

:required

input:required

Selects <input> elements with a "required" attribute specified

:root

root

Selects the document's root element

: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

CSS Opacity / Transparency

The opacity property specifies the opacity/transparency of an element.

Transparent Image

The opacity property can take a value from 0.0 - 1.0. The lower the value, the more transparent:

Forest

opacity 0.2

Forest

opacity 0.5

Forest

opacity 1
(default)

Example

img {
  opacity: 0.5;
}

 

CSS Navigation Bar

Demo: Navigation Bars

Vertical

·         Home

·         News

·         Contact

·         About

Horizontal

·         Home

·         News

·         Contact

·         About



·         Home

·         News

·         Contact

·         About

Navigation Bars

Having easy-to-use navigation is important for any web site.

With CSS you can transform boring HTML menus into good-looking navigation bars.

Navigation Bar = List of Links

A navigation bar needs standard HTML as a base.

In our examples we will build the navigation bar from a standard HTML list.

A navigation bar is basically a list of links, so using the <ul> and <li> elements makes perfect sense:

Example

<ul>
  
<li><a href="default.asp">Home</a></li>
  
<li><a href="news.asp">News</a></li>
  
<li><a href="contact.asp">Contact</a></li>
  
<li><a href="about.asp">About</a></li>
</ul>

Now let's remove the bullets and the margins and padding from the list:

Example

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

Example explained:

  • list-style-type: none; - Removes the bullets. A navigation bar does not need list markers
  • Set margin: 0; and padding: 0; to remove browser default settings

The code in the example above is the standard code used in both vertical, and horizontal navigation bars, which you will learn more about in the next chapters.

CSS Vertical Navigation Bar

Vertical Navigation Bar

·         Home

·         News

·         Contact

·         About

To build a vertical navigation bar, you can style the <a> elements inside the list, in addition to the code from the previous page:

Example

li a {
  display: block;
  width: 60px;
}

Example explained:

  • display: block; - Displaying the links as block elements makes the whole link area clickable (not just the text), and it allows us to specify the width (and padding, margin, height, etc. if you want)
  • width: 60px; - Block elements take up the full width available by default. We want to specify a 60 pixels width

You can also set the width of <ul>, and remove the width of <a>, as they will take up the full width available when displayed as block elements. This will produce the same result as our previous example:

Example

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 60px;
}

li a {
  display: block;
}

Vertical Navigation Bar Examples

Create a basic vertical navigation bar with a gray background color and change the background color of the links when the user moves the mouse over them:

·         Home

·         News

·         Contact

·         About

Example

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 200px;
  background-color: #f1f1f1;
}

li a {
  display: block;
  color: #000;
  padding: 8px 16px;
  text-decoration: none;
}

/* Change the link color on hover */
li a:hover {
  background-color: #555;
  color: white;
}

Active/Current Navigation Link

Add an "active" class to the current link to let the user know which page he/she is on:

·         Home

·         News

·         Contact

·         About

Example

.active {
  background-color: #04AA6D;
  color: white;
}

Gray Horizontal Navbar

An example of a gray horizontal navigation bar with a thin gray border:

·         Home

·         News

·         Contact

·         About

Example

ul {
  border: 1px solid #e7e7e7;
  background-color: #f3f3f3;
}

li a {
  color: #666;
}

CSS Dropdowns


Create a hoverable dropdown with CSS.


 

Basic Dropdown

Create a dropdown box that appears when the user moves the mouse over an element.

Example

<style>
.dropdown 
{
  position
: relative;
  display
: inline-block;
}

.dropdown-content 
{
  display
: none;
  position
: absolute;
  background-color
: #f9f9f9;
  min-width
: 160px;
  box-shadow
: 0px 8px 16px 0px rgba(0,0,0,0.2);
  padding
: 12px 16px;
  z-index
: 1;
}

.dropdown:hover .dropdown-content 
{
  display
: block;
}
</style>

<div class="dropdown">
  
<span>Mouse over me</span>
  
<div class="dropdown-content">
    
<p>Hello World!</p>
  
</div>
</div>

Example Explained

HTML) Use any element to open the dropdown content, e.g. a <span>, or a <button> element.

Use a container element (like <div>) to create the dropdown content and add whatever you want inside of it.

Wrap a <div> element around the elements to position the dropdown content correctly with CSS.

CSS) The .dropdown class uses position:relative, which is needed when we want the dropdown content to be placed right below the dropdown button (using position:absolute).

The .dropdown-content class holds the actual dropdown content. It is hidden by default, and will be displayed on hover (see below). Note the min-width is set to 160px. Feel free to change this. Tip: If you want the width of the dropdown content to be as wide as the dropdown button, set the width to 100% (and overflow:auto to enable scroll on small screens).

Instead of using a border, we have used the CSS box-shadow property to make the dropdown menu look like a "card".

The :hover selector is used to show the dropdown menu when the user moves the mouse over the dropdown button.

Dropdown Menu

Create a dropdown menu that allows the user to choose an option from a list:

Dropdown Menu

This example is similar to the previous one, except that we add links inside the dropdown box and style them to fit a styled dropdown button:

Example

<style>
/* Style The Dropdown Button */
.dropbtn 
{
  background-color
: #4CAF50;
  color
: white;
  padding
: 16px;
  font-size
: 16px;
  border
: none;
  cursor
: pointer;
}

/* The container <div> - needed to position the dropdown content */
.dropdown 
{
  position
: relative;
  display
: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content 
{
  display
: none;
  position
: absolute;
  background-color
: #f9f9f9;
  min-width
: 160px;
  box-shadow
: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index
: 1;
}

/* Links inside the dropdown */
.dropdown-content a 
{
  color
: black;
  padding
: 12px 16px;
  text-decoration
: none;
  display
: block;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover 
{background-color: #f1f1f1}

/* Show the dropdown menu on hover */
.dropdown:hover .dropdown-content 
{
  display
: block;
}

/* Change the background color of the dropdown button when the dropdown content is shown */
.dropdown:hover .dropbtn 
{
  background-color
: #3e8e41;
}
</style>

<div class="dropdown">
  
<button class="dropbtn">Dropdown</button>
  
<div class="dropdown-content">
    
<a href="#">Link 1</a>
    
<a href="#">Link 2</a>
    
<a href="#">Link 3</a>
  
</div>
</div>

CSS Image Gallery

CSS can be used to create an image gallery.

Cinque Terre

Add a description of the image here

Forest

Add a description of the image here

Northern Lights

Add a description of the image here

Mountains

Add a description of the image here


Image Gallery

The following image gallery is created with CSS:

Example

<html>
<head>
<style>
div.gallery {
  margin: 5px;
  border: 1px solid #ccc;
  float: left;
  width: 180px;
}

div.gallery:hover {
  border: 1px solid #777;
}

div.gallery img {
  width: 100%;
  height: auto;
}

div.desc {
  padding: 15px;
  text-align: center;
}
</style>
</head>
<body>

<div class="gallery">
  
<a target="_blank" href="img_5terre.jpg">
    
<img src="img_5terre.jpg" alt="Cinque Terre" width="600" height="400">
  
</a>
  
<div class="desc">Add a description of the image here</div>
</div>

<div class="gallery">
  
<a target="_blank" href="img_forest.jpg">
    
<img src="img_forest.jpg" alt="Forest" width="600" height="400">
  
</a>
  
<div class="desc">Add a description of the image here</div>
</div>

<div class="gallery">
  
<a target="_blank" href="img_lights.jpg">
    
<img src="img_lights.jpg" alt="Northern Lights" width="600" height="400">
  
</a>
  
<div class="desc">Add a description of the image here</div>
</div>

<div class="gallery">
  
<a target="_blank" href="img_mountains.jpg">
    
<img src="img_mountains.jpg" alt="Mountains" width="600" height="400">
  
</a>
  
<div class="desc">Add a description of the image here</div>
</div>

</body>
</html>

CSS Image Sprites

❮ PreviousNext ❯

Image Sprites

An image sprite is a collection of images put into a single image.

A web page with many images can take a long time to load and generates multiple server requests.

Using image sprites will reduce the number of server requests and save bandwidth.


Image Sprites - Simple Example

Instead of using three separate images, we use this single image ("img_navsprites.gif"):

navigation images

With CSS, we can show just the part of the image we need.

In the following example the CSS specifies which part of the "img_navsprites.gif" image to show:

Example

#home {
  width: 46px;
  height: 44px;
  background: url(img_navsprites.gif) 0 0;
}

Example explained:

  • <img id="home" src="img_trans.gif"> - Only defines a small transparent image because the src attribute cannot be empty. The displayed image will be the background image we specify in CSS
  • width: 46px; height: 44px; - Defines the portion of the image we want to use
  • background: url(img_navsprites.gif) 0 0; - Defines the background image and its position (left 0px, top 0px)

This is the easiest way to use image sprites, now we want to expand it by using links and hover effects.

Image Sprites - Create a Navigation List

We want to use the sprite image ("img_navsprites.gif") to create a navigation list.

We will use an HTML list, because it can be a link and also supports a background image:

Example

#navlist {
  position: relative;
}

#navlist li {
  margin: 0;
  padding: 0;
  list-style: none;
  position: absolute;
  top: 0;
}

#navlist li, #navlist a {
  height: 44px;
  display: block;
}

#home {
  left: 0px;
  width: 46px;
  background: url('img_navsprites.gif') 0 0;
}

#prev {
  left: 63px;
  width: 43px;
  background: url('img_navsprites.gif') -47px 0;
}

#next {
  left: 129px;
  width: 43px;
  background: url('img_navsprites.gif') -91px 0;
}

Example explained:

  • #navlist {position:relative;} - position is set to relative to allow absolute positioning inside it
  • #navlist li {margin:0;padding:0;list-style:none;position:absolute;top:0;} - margin and padding are set to 0, list-style is removed, and all list items are absolute positioned
  • #navlist li, #navlist a {height:44px;display:block;} - the height of all the images is 44px

Now start to position and style for each specific part:

  • #home {left:0px;width:46px;} - Positioned all the way to the left, and the width of the image is 46px
  • #home {background:url(img_navsprites.gif) 0 0;} - Defines the background image and its position (left 0px, top 0px)
  • #prev {left:63px;width:43px;} - Positioned 63px to the right (#home width 46px + some extra space between items), and the width is 43px
  • #prev {background:url('img_navsprites.gif') -47px 0;} - Defines the background image 47px to the right (#home width 46px + 1px line divider)
  • #next {left:129px;width:43px;} - Positioned 129px to the right (start of #prev is 63px + #prev width 43px + extra space), and the width is 43px
  • #next {background:url('img_navsprites.gif') -91px 0;} - Defines the background image 91px to the right (#home width 46px + 1px line divider + #prev width 43px + 1px line divider)

Image Sprites - Hover Effect

Now we want to add a hover effect to our navigation list.

Tip: The :hover selector can be used on all elements, not only on links.

Our new image ("img_navsprites_hover.gif") contains three navigation images and three images to use for hover effects:

navigation images

Because this is one single image, and not six separate files, there will be no loading delay when a user hovers over the image.

We only add three lines of code to add the hover effect:

Example

#home a:hover {
  background: url('img_navsprites_hover.gif') 0 -45px;
}

#prev a:hover {
  background: url('img_navsprites_hover.gif') -47px -45px;
}

#next a:hover {
  background: url('img_navsprites_hover.gif') -91px -45px;
}

Example explained:

  • #home a:hover {background: url('img_navsprites_hover.gif') 0 -45px;} - For all three hover images we specify the same background position, only 45px further down

CSS Forms

3`The look of an HTML form can be greatly improved with CSS:

Top of Form

First Name  Last Name  Country               Try it Yourself »

Bottom of Form

Styling Input Fields

Use the width property to determine the width of the input field:

First Name 

Example

input {
  width: 100%;
}

The example above applies to all <input> elements. If you only want to style a specific input type, you can use attribute selectors:

  • input[type=text] - will only select text fields
  • input[type=password] - will only select password fields
  • input[type=number] - will only select number fields
  • etc..

 

Padded Inputs

Use the padding property to add space inside the text field.

Tip: When you have many inputs after each other, you might also want to add some margin, to add more space outside of them:

First Name  Last Name 

Example

input[type=text] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  box-sizing: border-box;
}

Note that we have set the box-sizing property to border-box. This makes sure that the padding and eventually borders are included in the total width and height of the elements.

Bordered Inputs

Use the border property to change the border size and color, and use the border-radius property to add rounded corners:

First Name 

Example

input[type=text] {
  border: 2px solid red;
  border-radius: 4px;
}

If you only want a bottom border, use the border-bottom property:

First Name 

Example

input[type=text] {
  border: none;
  border-bottom: 2px solid red;
}

Colored Inputs

Use the background-color property to add a background color to the input, and the color property to change the text color:

Example

input[type=text] {
  background-color: #3CBC8D;
  color: white;
}

Focused Inputs

By default, some browsers will add a blue outline around the input when it gets focus (clicked on). You can remove this behavior by adding outline: none; to the input.

Use the :focus selector to do something with the input field when it gets focus:

Example

input[type=text]:focus {
  background-color: lightblue;
}

Example

input[type=text]:focus {
  border: 3px solid #555;
}

Input with icon/image

If you want an icon inside the input, use the background-image property and position it with the background-position property. Also notice that we add a large left padding to reserve the space of the icon:

Example

input[type=text] {
  background-color: white;
  background-image: url('searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  padding-left: 40px;
}

Animated Search Input

In this example we use the CSS transition property to animate the width of the search input when it gets focus.

Example

input[type=text] {
  transition: width 0.4s ease-in-out;
}

input[type=text]:focus {
  width: 100%;
}

Styling Textareas

Tip: Use the resize property to prevent textareas from being resized (disable the "grabber" in the bottom right corner):

Example

textarea {
  width: 100%;
  height: 150px;
  padding: 12px 20px;
  box-sizing: border-box;
  border: 2px solid #ccc;
  border-radius: 4px;
  background-color: #f8f8f8;
  resize: none;
}

Styling Select Menus

Top of Form

             

Bottom of Form

Example

select {
  width: 100%;
  padding: 16px 20px;
  border: none;
  border-radius: 4px;
  background-color: #f1f1f1;
}

Styling Input Buttons

 

Example

input[type=button], input[type=submit], input[type=reset] {
  background-color: #04AA6D;
  border: none;
  color: white;
  padding: 16px 32px;
  text-decoration: none;
  margin: 4px 2px;
  cursor: pointer;
}

/* Tip: use width: 100% for full-width buttons */

Responsive Form

Resize the browser window to see the effect. When the screen is less than 600px wide, make the two columns stack on top of each other instead of next to each other.

CSS Counters

Pizza

Hamburger

Hotdogs

CSS counters are "variables" maintained by CSS whose values can be incremented by CSS rules (to track how many times they are used). Counters let you adjust the appearance of content based on its placement in the document.


Automatic Numbering With Counters

CSS counters are like "variables". The variable values can be incremented by CSS rules (which will track how many times they are used).

To work with CSS counters we will use the following properties:

  • counter-reset - Creates or resets a counter
  • counter-increment - Increments a counter value
  • content - Inserts generated content
  • counter() or counters() function - Adds the value of a counter to an element

To use a CSS counter, it must first be created with counter-reset.

The following example creates a counter for the page (in the body selector), then increments the counter value for each <h2> element and adds "Section <value of the counter>:" to the beginning of each <h2> element:

Example

body {
  counter-reset: section;
}

h2::before {
  counter-increment: section;
  content: "Section " counter(section) ": ";
}

Nesting Counters

The following example creates one counter for the page (section) and one counter for each <h1> element (subsection). The "section" counter will be counted for each <h1> element with "Section <value of the section counter>.", and the "subsection" counter will be counted for each <h2> element with "<value of the section counter>.<value of the subsection counter>":

Example

body {
  counter-reset: section;
}

h1 {
  counter-reset: subsection;
}

h1::before {
  counter-increment: section;
  content: "Section " counter(section) ". ";
}

h2::before {
  counter-increment: subsection;
  content: counter(section) "." counter(subsection) " ";
}

A counter can also be useful to make outlined lists because a new instance of a counter is automatically created in child elements. Here we use the counters() function to insert a string between different levels of nested counters:

Example

ol {
  counter-reset: section;
  list-style-type: none;
}

li::before {
  counter-increment: section;
  content: counters(section,".") " ";
}

 CSS Counter Properties

Property

Description

content

Used with the ::before and ::after pseudo-elements, to insert generated content

counter-increment

Increments one or more counter values

counter-reset

Creates or resets one or more counters

counter()

Returns the current value of the named counter

CSS Website Layout

Website Layout

A website is often divided into headers, menus, content and a footer:

Header

Navigation Menu

Content

Main Content

Content

Footer

There are tons of different layout designs to choose from. However, the structure above, is one of the most common, and we will take a closer look at it in this tutorial.

Header

A header is usually located at the top of the website (or right below a top navigation menu). It often contains a logo or the website name:

Example

.header {
  background-color: #F1F1F1;
  text-align: center;
  padding: 20px;
}

Result

Header

Navigation Bar

A navigation bar contains a list of links to help visitors navigating through your website:

Example

/* The navbar container */
.topnav {
  overflow: hidden;
  background-color: #333;
}

/* Navbar links */
.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

/* Links - change color on hover */
.topnav a:hover {
  background-color: #ddd;
  color: black;
}

Result

LinkLinkLink

Content

The layout in this section, often depends on the target users. The most common layout is one (or combining them) of the following:

  • 1-column (often used for mobile browsers)
  • 2-column (often used for tablets and laptops)
  • 3-column layout (only used for desktops)

1-column:

2-column:

3-column:

We will create a 3-column layout, and change it to a 1-column layout on smaller screens:

Example

/* Create three equal columns that float next to each other */
.column {
  float: left;
  width: 33.33%;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

/* Responsive layout - makes the three columns stack on top of each other instead of next to each other on smaller screens (600px wide or less) */
@media screen and (max-width: 600px) {
  .column {
    width: 100%;
  }
}

Result

Column

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique.

Column

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique.

Column

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique.

Unequal Columns

The main content is the biggest and the most important part of your site.

It is common with unequal column widths, so that most of the space is reserved for the main content. The side content (if any) is often used as an alternative navigation or to specify information relevant to the main content. Change the widths as you like, only remember that it should add up to 100% in total:

Example

.column {
  float: left;
}

/* Left and right column */
.column.side {
  width: 25%;
}

/* Middle column */
.column.middle {
  width: 50%;
}

/* Responsive layout - makes the three columns stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) {
  .column.side, .column.middle {
    width: 100%;
  }
}

Result

Side

Lorem ipsum dolor sit amet, consectetur adipiscing elit...

Main Content

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique. Quisque vehicula, risus eget aliquam placerat, purus leo tincidunt eros, eget luctus quam orci in velit. Praesent scelerisque tortor sed accumsan convallis.

Side

Lorem ipsum dolor sit amet, consectetur adipiscing elit...

Footer

The footer is placed at the bottom of your page. It often contains information like copyright and contact info:

Example

.footer {
  background-color: #F1F1F1;
  text-align: center;
  padding: 10px;
}

Result

Footer

Responsive Website Layout

By using some of the CSS code above, we have created a responsive website layout, which varies between two columns and full-width columns depending on screen width:

CSS Units

CSS has several different units for expressing a length.

Many CSS properties take "length" values, such as widthmarginpaddingfont-size, etc.

Length is a number followed by a length unit, such as 10px2em, etc.

Example

Set different length values, using px (pixels):

h1 {
  font-size: 60px;
}

{
  font-size: 25px;
  line-height: 50px;
}

Note: A whitespace cannot appear between the number and the unit. However, if the value is 0, the unit can be omitted.

For some CSS properties, negative lengths are allowed.

There are two types of length units: absolute and relative.

Absolute Lengths

The absolute length units are fixed and a length expressed in any of these will appear as exactly that size.

Absolute length units are not recommended for use on screen, because screen sizes vary so much. However, they can be used if the output medium is known, such as for print layout.

Unit

Description

cm

centimeters

mm

millimeters

in

inches (1in = 96px = 2.54cm)

px *

pixels (1px = 1/96th of 1in)

pt

points (1pt = 1/72 of 1in)

pc

picas (1pc = 12 pt)

* Pixels (px) are relative to the viewing device. For low-dpi devices, 1px is one device pixel (dot) of the display. For printers and high resolution screens 1px implies multiple device pixels.

Relative Lengths

Relative length units specify a length relative to another length property. Relative length units scale better between different rendering mediums.

Unit

Description

em

Relative to the font-size of the element (2em means 2 times the size of the current font)

Try it

ex

Relative to the x-height of the current font (rarely used)

Try it

ch

Relative to width of the "0" (zero)

Try it

rem

Relative to font-size of the root element

Try it

vw

Relative to 1% of the width of the viewport*

Try it

vh

Relative to 1% of the height of the viewport*

Try it

vmin

Relative to 1% of viewport's* smaller dimension

Try it

vmax

Relative to 1% of viewport's* larger dimension

Try it

%

Relative to the parent element

Try it

Tip: The em and rem units are practical in creating perfectly scalable layout!
* Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm.

CSS The !important Rule

What is !important?

The !important rule in CSS is used to add more importance to a property/value than normal.

In fact, if you use the !important rule, it will override ALL previous styling rules for that specific property on that element!

Let us look at an example:

Example

#myid {
  background-color: blue;
}

.myclass {
  background-color: gray;
}

{
  background-color: red !important;
}

Example Explained

In the example above. all three paragraphs will get a red background color, even though the ID selector and the class selector have a higher specificity. The !important rule overrides the background-color property in both cases.


Important About !important

The only way to override an !important rule is to include another !important rule on a declaration with the same (or higher) specificity in the source code - and here the problem starts! This makes the CSS code confusing and the debugging will be hard, especially if you have a large style sheet!

Here we have created a simple example. It is not very clear, when you look at the CSS source code, which color is considered most important:

Example

#myid {
  background-color: blue !important;
}

.myclass {
  background-color: gray !important;
}

{
  background-color: red !important;
}

Tip: It is good to know about the !important rule. You might see it in some CSS source code. However, do not use it unless you absolutely have to.

Maybe One or Two Fair Uses of !important

One way to use !important is if you have to override a style that cannot be overridden in any other way. This could be if you are working on a Content Management System (CMS) and cannot edit the CSS code. Then you can set some custom styles to override some of the CMS styles.

Another way to use !important is: Assume you want a special look for all buttons on a page. Here, buttons are styled with a gray background color, white text, and some padding and border:

Example

.button {
  background-color: #8c8c8c;
  color: white;
  padding: 5px;
  border: 1px solid black;
}

The look of a button can sometimes change if we put it inside another element with higher specificity, and the properties get in conflict. Here is an example of this:

Example

.button {
  background-color: #8c8c8c;
  color: white;
  padding: 5px;
  border: 1px solid black;
}

#myDiv a {
  color: red;
  background-color: yellow;
}

To "force" all buttons to have the same look, no matter what, we can add the !important rule to the properties of the button, like this:

Example

.button {
  background-color: #8c8c8c !important;
  color: white !important;
  padding: 5px !important;
  border: 1px solid black !important;
}

#myDiv a {
  color: red;
  background-color: yellow;
}

CSS Math Functions

❮ PreviousNext ❯


The CSS math functions allow mathematical expressions to be used as property values. Here, we will explain the calc()max() and min() functions.


The calc() Function

The calc() function performs a calculation to be used as the property value.

CSS Syntax

calc(expression)

Value

Description

expression

Required. A mathematical expression. The result will be used as the value.
The following operators can be used: + - * /

Let us look at an example:

Example

Use calc() to calculate the width of a <div> element:

#div1 {
  position: absolute;
  left: 50px;
  width: calc(100% - 100px);
  border: 1px solid black;
  background-color: yellow;
  padding: 5px;
}

The max() Function

The max() function uses the largest value, from a comma-separated list of values, as the property value.

CSS Syntax

max(value1value2, ...)

Value

Description

value1value2, ...

Required. A list of comma-separated values - where the largest value is chosen

Let us look at an example:

Example

Use max() to set the width of #div1 to whichever value is largest, 50% or 300px:

#div1 {
  background-color: yellow;
  height: 100px;
  width: max(50%, 300px);
}

The min() Function

The min() function uses the smallest value, from a comma-separated list of values, as the property value.

CSS Syntax

min(value1value2, ...)

Value

Description

value1value2, ...

Required. A list of comma-separated values - where the smallest value is chosen

Let us look at an example:

Example

Use min() to set the width of #div1 to whichever value is smallest, 50% or 300px:

#div1 {
  background-color: yellow;
  height: 100px;
  width: min(50%, 300px);
}

All CSS Math Functions

Function

Description

calc()

Allows you to perform calculations to determine CSS property values

max()

Uses the largest value, from a comma-separated list of values, as the property value

min()

Uses the smallest value, from a comma-separated list of values, as the property value

 

CSS Introduction

Next ❯

CSS is the language we use to style an HTML document.

CSS describes how HTML elements should be displayed.

This tutorial will teach you CSS from basic to advanced.

Examples in Each Chapter

This CSS tutorial contains hundreds of CSS examples.

With our online editor, you can edit the CSS, and click on a button to view the result.

CSS Example

body {
  background-color: lightblue;
}

h1 {
  color: white;
  text-align: center;
}

{
  font-family: verdana;
  font-size: 20px;
}

Click on the "Try it Yourself" button to see how it works.

CSS Introduction

CSS is the language we use to style a Web page.


What is CSS?

  • CSS stands for Cascading Style Sheets
  • CSS describes how HTML elements are to be displayed on screen, paper, or in other media
  • CSS saves a lot of work. It can control the layout of multiple web pages all at once
  • External stylesheets are stored in CSS files

CSS Demo - One HTML Page - Multiple Styles!

Here we will show one HTML page displayed with four different stylesheets. Click on the "Stylesheet 1", "Stylesheet 2", "Stylesheet 3", "Stylesheet 4" links below to see the different styles:

Why Use CSS?

CSS is used to define styles for your web pages, including the design, layout and variations in display for different devices and screen sizes.

CSS Example

body {
  background-color: lightblue;
}

h1 {
  color: white;
  text-align: center;
}

{
  font-family: verdana;
  font-size: 20px;
}


CSS Solved a Big Problem

HTML was NEVER intended to contain tags for formatting a web page!

HTML was created to describe the content of a web page, like:

<h1>This is a heading</h1>

<p>This is a paragraph.</p>

When tags like <font>, and color attributes were added to the HTML 3.2 specification, it started a nightmare for web developers. Development of large websites, where fonts and color information were added to every single page, became a long and expensive process.

CSS Saves a Lot of Work!

The style definitions are normally saved in external .css files.

With an external stylesheet file, you can change the look of an entire website by changing just one file!

 

CSS Syntax

A CSS rule consists of a selector and a declaration block.

CSS Syntax

CSS selector

The selector points to the HTML element you want to style.

The declaration block contains one or more declarations separated by semicolons.

Each declaration includes a CSS property name and a value, separated by a colon.

Multiple CSS declarations are separated with semicolons, and declaration blocks are surrounded by curly braces.

Example

In this example all <p> elements will be center-aligned, with a red text color:

{
  color
: red;
  text-align
: center;
}

Example Explained

  • p is a selector in CSS (it points to the HTML element you want to style: <p>).
  • color is a property, and red is the property value
  • text-align is a property, and center is the property value

You will learn much more about CSS selectors and CSS properties in the next chapters!

CSS Selectors

A CSS selector selects the HTML element(s) you want to style.

CSS Selectors

CSS selectors are used to "find" (or select) the HTML elements you want to style.

We can divide CSS selectors into five categories:

  • Simple selectors (select elements based on name, id, class)
  • Combinator selectors (select elements based on a specific relationship between them)
  • Pseudo-class selectors (select elements based on a certain state)
  • Pseudo-elements selectors (select and style a part of an element)
  • Attribute selectors (select elements based on an attribute or attribute value)

This page will explain the most basic CSS selectors.


The CSS element Selector

The element selector selects HTML elements based on the element name.

Example

Here, all <p> elements on the page will be center-aligned, with a red text color: 

{
  text-align: center;
  color: red;
}

The CSS id Selector

The id selector uses the id attribute of an HTML element to select a specific element.

The id of an element is unique within a page, so the id selector is used to select one unique element!

To select an element with a specific id, write a hash (#) character, followed by the id of the element.

Example

The CSS rule below will be applied to the HTML element with id="para1": 

#para1 {
  text-align: center;
  color: red;
}

Note: An id name cannot start with a number!

 

The CSS class Selector

The class selector selects HTML elements with a specific class attribute.

To select elements with a specific class, write a period (.) character, followed by the class name.

Example

In this example all HTML elements with class="center" will be red and center-aligned: 

.center {
  text-align: center;
  color: red;
}

You can also specify that only specific HTML elements should be affected by a class.

Example

In this example only <p> elements with class="center" will be red and center-aligned: 

p.center {
  text-align: center;
  color: red;
}

HTML elements can also refer to more than one class.

Example

In this example the <p> element will be styled according to class="center" and to class="large": 

<p class="center large">This paragraph refers to two classes.</p>

Note: A class name cannot start with a number!


The CSS Universal Selector

The universal selector (*) selects all HTML elements on the page.

Example

The CSS rule below will affect every HTML element on the page: 

{
  text-align: center;
  color: blue;
}

The CSS Grouping Selector

The grouping selector selects all the HTML elements with the same style definitions.

Look at the following CSS code (the h1, h2, and p elements have the same style definitions):

h1 {
  text-align: center;
  color: red;
}

h2 {
  text-align: center;
  color: red;
}

{
  text-align: center;
  color: red;
}

It will be better to group the selectors, to minimize the code.

To group selectors, separate each selector with a comma.

Example

In this example we have grouped the selectors from the code above: 

h1, h2, p {
  text-align: center;
  color: red;
}


All CSS Simple Selectors

Selector

Example

Example description

#id

#firstname

Selects the element with id="firstname"

.class

.intro

Selects all elements with class="intro"

element.class

p.intro

Selects only <p> elements with class="intro"

*

*

Selects all elements

element

p

Selects all <p> elements

element,element,..

div, p

Selects all <div> elements and all <p> elements

 

 

How To Add CSS

When a browser reads a style sheet, it will format the HTML document according to the information in the style sheet.

Three Ways to Insert CSS

There are three ways of inserting a style sheet:

  • External CSS
  • Internal CSS
  • Inline CSS

External CSS

With an external style sheet, you can change the look of an entire website by changing just one file!

Each HTML page must include a reference to the external style sheet file inside the <link> element, inside the head section.

Example

External styles are defined within the <link> element, inside the <head> section of an HTML page:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

An external style sheet can be written in any text editor, and must be saved with a .css extension.

The external .css file should not contain any HTML tags.

Here is how the "mystyle.css" file looks:

"mystyle.css"

body {
  background-color: lightblue;
}

h1 {
  color: navy;
  margin-left: 20px;
}

Note: Do not add a space between the property value and the unit:
Incorrect (space): 
margin-left: 20 px;
Correct (nospace): 
margin-left: 20px;

Internal CSS

An internal style sheet may be used if one single HTML page has a unique style.

The internal style is defined inside the <style> element, inside the head section.

Example

Internal styles are defined within the <style> element, inside the <head> section of an HTML page:

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-color: linen;
}

h1 {
  color: maroon;
  margin-left: 40px;
}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

Inline CSS

An inline style may be used to apply a unique style for a single element.

To use inline styles, add the style attribute to the relevant element. The style attribute can contain any CSS property.

Example

Inline styles are defined within the "style" attribute of the relevant element:

<!DOCTYPE html>
<html>
<body>

<h1 style="color:blue;text-align:center;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>

</body>
</html>

Tip: An inline style loses many of the advantages of a style sheet (by mixing content with presentation). Use this method sparingly.

Multiple Style Sheets

If some properties have been defined for the same selector (element) in different style sheets, the value from the last read style sheet will be used. 

Assume that an external style sheet has the following style for the <h1> element:

h1 {
  color: navy;
}

Then, assume that an internal style sheet also has the following style for the <h1> element:

h1 {
  color: orange;   
}

Example

If the internal style is defined after the link to the external style sheet, the <h1> elements will be "orange":

<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<style>
h1 {
  color: orange;
}
</style>
</head>

Example

However, if the internal style is defined before the link to the external style sheet, the <h1> elements will be "navy": 

<head>
<style>
h1 {
  color: orange;
}
</style>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

Cascading Order

What style will be used when there is more than one style specified for an HTML element?

All the styles in a page will "cascade" into a new "virtual" style sheet by the following rules, where number one has the highest priority:

  1. Inline style (inside an HTML element)
  2. External and internal style sheets (in the head section)
  3. Browser default

So, an inline style has the highest priority, and will override external and internal styles and browser defaults.

Top of Form

CSS Comments

CSS comments are not displayed in the browser, but they can help document your source code.

CSS Comments

Comments are used to explain the code, and may help when you edit the source code at a later date.

Comments are ignored by browsers.

A CSS comment is placed inside the <style> element, and starts with /* and ends with */:

Example

/* This is a single-line comment */
{
  color: red;
}

You can add comments wherever you want in the code:

Example

{
  color: red;  /* Set text color to red */
}

Comments can also span multiple lines: 

Example

/* This is
a multi-line
comment */

{
  color: red;
}

HTML and CSS Comments

From the HTML tutorial, you learned that you can add comments to your HTML source by using the <!--...--> syntax.

In the following example, we use a combination of HTML and CSS comments:

Example

<!DOCTYPE html>
<html>
<head>
<style>
{
  color: red; /* Set text color to red */
}
</style>
</head>
<body>

<h2>My Heading</h2>

<!-- These paragraphs will be red -->
<p>Hello World!</p>
<p>This paragraph is styled with CSS.</p>
<p>CSS comments are not shown in the output.</p>

</body>
</html>

CSS Colors

Colors are specified using predefined color names, or RGB, HEX, HSL, RGBA, HSLA values.

CSS Color Names

In CSS, a color can be specified by using a predefined color name:

Tomato

Orange

DodgerBlue

MediumSeaGreen

Gray

SlateBlue

Violet


CSS Background Color

You can set the background color for HTML elements:

Hello World

 


Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Example

<h1 style="background-color:DodgerBlue;">Hello World</h1>
<p style="background-color:Tomato;">Lorem ipsum...</p>

CSS Text Color

You can set the color of text:

Hello World

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Example

<h1 style="color:Tomato;">Hello World</h1>
<p style="color:DodgerBlue;">Lorem ipsum...</p>
<p style="color:MediumSeaGreen;">Ut wisi enim...</p>

CSS Border Color

You can set the color of borders:

Hello World

Hello World

Hello World

Example

<h1 style="border:2px solid Tomato;">Hello World</h1>
<h1 style="border:2px solid DodgerBlue;">Hello World</h1>
<h1 style="border:2px solid Violet;">Hello World</h1>

CSS Color Values

In CSS, colors can also be specified using RGB values, HEX values, HSL values, RGBA values, and HSLA values:

Same as color name "Tomato":

rgb(255, 99, 71)

#ff6347

hsl(9, 100%, 64%)

Example

<h1 style="background-color:rgb(255, 99, 71);">...</h1>
<h1 style="background-color:#ff6347;">...</h1>
<h1 style="background-color:hsl(9, 100%, 64%);">...</h1>

<h1 style="background-color:rgba(255, 99, 71, 0.5);">...</h1>
<h1 style="background-color:hsla(9, 100%, 64%, 0.5);">...</h1>

CSS Backgrounds

The CSS background properties are used to add background effects for elements.

In these chapters, you will learn about the following CSS background properties:

  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position
  • background (shorthand property)

CSS background-color

The background-color property specifies the background color of an element.

Example

The background color of a page is set like this:

body {
  background-color: lightblue;
}

With CSS, a color is most often specified by:

  • a valid color name - like "red"
  • a HEX value - like "#ff0000"
  • an RGB value - like "rgb(255,0,0)"

Other Elements

You can set the background color for any HTML elements:

Example

Here, the <h1>, <p>, and <div> elements will have different background colors: 

h1 {
  background-color: green;
}

div {
  background-color: lightblue;
}

{
  background-color: yellow;
}

Opacity / Transparency

The opacity property specifies the opacity/transparency of an element. It can take a value from 0.0 - 1.0. The lower value, the more transparent:

opacity 1

opacity 0.6

opacity 0.3

opacity 0.1

Example

div {
  background-color: green;
  opacity: 0.3;
}

Note: When using the opacity property to add transparency to the background of an element, all of its child elements inherit the same transparency. This can make the text inside a fully transparent element hard to read.

Transparency using RGBA

If you do not want to apply opacity to child elements, like in our example above, use RGBA color values. The following example sets the opacity for the background color and not the text:

100% opacity

60% opacity

30% opacity

10% opacity

An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).

Example

div {
  background: rgba(0, 128, 0, 0.3) /* Green background with 30% opacity */
}

The CSS Background Color Property

Property

Description

background-color

Sets the background color of an element

 

CSS Borders

The CSS border properties allow you to specify the style, width, and color of an element's border.

I have borders on all sides.

I have a red bottom border.

I have rounded borders.

I have a blue left border.

CSS Border Style

The border-style property specifies what kind of border to display.

The following values are allowed:

  • dotted - Defines a dotted border
  • dashed - Defines a dashed border
  • solid - Defines a solid border
  • double - Defines a double border
  • groove - Defines a 3D grooved border. The effect depends on the border-color value
  • ridge - Defines a 3D ridged border. The effect depends on the border-color value
  • inset - Defines a 3D inset border. The effect depends on the border-color value
  • outset - Defines a 3D outset border. The effect depends on the border-color value
  • none - Defines no border
  • hidden - Defines a hidden border

The border-style property can have from one to four values (for the top border, right border, bottom border, and the left border).

Example

Demonstration of the different border styles:

p.dotted {border-style: dotted;}
p.dashed {border-style: dashed;}
p.solid {border-style: solid;}
p.double {border-style: double;}
p.groove {border-style: groove;}
p.ridge {border-style: ridge;}
p.inset {border-style: inset;}
p.outset {border-style: outset;}
p.none {border-style: none;}
p.hidden {border-style: hidden;}
p.mix {border-style: dotted dashed solid double;}

Result:

A dotted border.

A dashed border.

A solid border.

A double border.

A groove border. The effect depends on the border-color value.

A ridge border. The effect depends on the border-color value.

An inset border. The effect depends on the border-color value.

An outset border. The effect depends on the border-color value.

No border.

A hidden border.

A mixed border.

Note: None of the OTHER CSS border properties (which you will learn more about in the next chapters) will have ANY effect unless the border-style property is set!

CSS Margins

Margins are used to create space around elements, outside of any defined borders.

This element has a margin of 70px.

CSS Margins

The CSS margin properties are used to create space around elements, outside of any defined borders.

With CSS, you have full control over the margins. There are properties for setting the margin for each side of an element (top, right, bottom, and left).

Margin - Individual Sides

CSS has properties for specifying the margin for each side of an element:

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

All the margin properties can have the following values:

  • auto - the browser calculates the margin
  • length - specifies a margin in px, pt, cm, etc.
  • % - specifies a margin in % of the width of the containing element
  • inherit - specifies that the margin should be inherited from the parent element

Tip: Negative values are allowed.

Example

Set different margins for all four sides of a <p> element:

{
  margin-top: 100px;
  margin-bottom: 100px;
  margin-right: 150px;
  margin-left: 80px;
}

Margin - Shorthand Property

To shorten the code, it is possible to specify all the margin properties in one property.

The margin property is a shorthand property for the following individual margin properties:

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

So, here is how it works:

If the margin property has four values:

  • margin: 25px 50px 75px 100px;
    • top margin is 25px
    • right margin is 50px
    • bottom margin is 75px
    • left margin is 100px

Example

Use the margin shorthand property with four values:

{
  margin: 25px 50px 75px 100px;
}

If the margin property has three values:

  • margin: 25px 50px 75px;
    • top margin is 25px
    • right and left margins are 50px
    • bottom margin is 75px

Example

Use the margin shorthand property with three values: 

{
  margin: 25px 50px 75px;
}

If the margin property has two values:

  • margin: 25px 50px;
    • top and bottom margins are 25px
    • right and left margins are 50px

Example

Use the margin shorthand property with two values: 

{
  margin: 25px 50px;
}

If the margin property has one value:

  • margin: 25px;
    • all four margins are 25px

Example

Use the margin shorthand property with one value: 

{
  margin: 25px;
}

The auto Value

You can set the margin property to auto to horizontally center the element within its container.

The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.

Example

Use margin: auto:

div {
  width: 300px;
  margin: auto;
  border: 1px solid red;
}

The inherit Value

This example lets the left margin of the <p class="ex1"> element be inherited from the parent element (<div>):

Example

Use of the inherit value:

div {
  border: 1px solid red;
  margin-left: 100px;
}

p.ex1 {
  margin-left: inherit;
}

All CSS Margin Properties

Property

Description

margin

A shorthand property for setting all the margin properties in one declaration

margin-bottom

Sets the bottom margin of an element

margin-left

Sets the left margin of an element

margin-right

Sets the right margin of an element

margin-top

Sets the top margin of an element

CSS Margin Collapse

Sometimes two margins collapse into a single margin.

Margin Collapse

Top and bottom margins of elements are sometimes collapsed into a single margin that is equal to the largest of the two margins.

This does not happen on left and right margins! Only top and bottom margins!

Look at the following example:

Example

Demonstration of margin collapse:

h1 {
  margin: 0 0 50px 0;
}

h2 {
  margin: 20px 0 0 0;
}

In the example above, the <h1> element has a bottom margin of 50px and the <h2> element has a top margin set to 20px.

Common sense would seem to suggest that the vertical margin between the <h1> and the <h2> would be a total of 70px (50px + 20px). But due to margin collapse, the actual margin ends up being 50px.

Bottom of Form


All CSS Margin Properties

Property

Description

margin

A shorthand property for setting all the margin properties in one declaration

margin-bottom

Sets the bottom margin of an element

margin-left

Sets the left margin of an element

margin-right

Sets the right margin of an element

margin-top

Sets the top margin of an element

 

CSS Padding

Padding is used to create space around an element's content, inside of any defined borders.

This element has a padding of 70px.

CSS Padding

The CSS padding properties are used to generate space around an element's content, inside of any defined borders.

With CSS, you have full control over the padding. There are properties for setting the padding for each side of an element (top, right, bottom, and left).

Padding - Individual Sides

CSS has properties for specifying the padding for each side of an element:

  • padding-top
  • padding-right
  • padding-bottom
  • padding-left

All the padding properties can have the following values:

  • length - specifies a padding in px, pt, cm, etc.
  • % - specifies a padding in % of the width of the containing element
  • inherit - specifies that the padding should be inherited from the parent element

Note: Negative values are not allowed.

Example

Set different padding for all four sides of a <div> element:  

div {
  padding-top: 50px;
  padding-right: 30px;
  padding-bottom: 50px;
  padding-left: 80px;
}

Padding - Shorthand Property

To shorten the code, it is possible to specify all the padding properties in one property.

The padding property is a shorthand property for the following individual padding properties:

  • padding-top
  • padding-right
  • padding-bottom
  • padding-left

So, here is how it works:

If the padding property has four values:

  • padding: 25px 50px 75px 100px;
    • top padding is 25px
    • right padding is 50px
    • bottom padding is 75px
    • left padding is 100px

Example

Use the padding shorthand property with four values:

div {
  padding: 25px 50px 75px 100px;
}

If the padding property has three values:

  • padding: 25px 50px 75px;
    • top padding is 25px
    • right and left paddings are 50px
    • bottom padding is 75px

Example

Use the padding shorthand property with three values: 

div {
  padding: 25px 50px 75px;
}

If the padding property has two values:

  • padding: 25px 50px;
    • top and bottom paddings are 25px
    • right and left paddings are 50px

Example

Use the padding shorthand property with two values: 

div {
  padding: 25px 50px;
}

If the padding property has one value:

  • padding: 25px;
    • all four paddings are 25px

Example

Use the padding shorthand property with one value: 

div {
  padding: 25px;
}

Padding and Element Width

The CSS width property specifies the width of the element's content area. The content area is the portion inside the padding, border, and margin of an element.

So, if an element has a specified width, the padding added to that element will be added to the total width of the element. This is often an undesirable result.

Example

Here, the <div> element is given a width of 300px. However, the actual width of the <div> element will be 350px (300px + 25px of left padding + 25px of right padding):

div {
  width: 300px;
  padding: 25px;
}

To keep the width at 300px, no matter the amount of padding, you can use the box-sizing property. This causes the element to maintain its actual width; if you increase the padding, the available content space will decrease.

Example

Use the box-sizing property to keep the width at 300px, no matter the amount of padding:

div {
  width: 300px;
  padding: 25px;
  box-sizing: border-box;
}

Bottom of Form

All CSS Padding Properties

Property

Description

padding

A shorthand property for setting all the padding properties in one declaration

padding-bottom

Sets the bottom padding of an element

padding-left

Sets the left padding of an element

padding-right

Sets the right padding of an element

padding-top

Sets the top padding of an element

CSS Height, Width and Max-width

The CSS height and width properties are used to set the height and width of an element.

The CSS max-width property is used to set the maximum width of an element.

This element has a height of 50 pixels and a width of 100%.

CSS Setting height and width

The height and width properties are used to set the height and width of an element.

The height and width properties do not include padding, borders, or margins. It sets the height/width of the area inside the padding, border, and margin of the element.

CSS height and width Values

The height and width properties may have the following values:

  • auto - This is default. The browser calculates the height and width
  • length - Defines the height/width in px, cm, etc.
  • % - Defines the height/width in percent of the containing block
  • initial - Sets the height/width to its default value
  • inherit - The height/width will be inherited from its parent value

CSS height and width Examples

This element has a height of 200 pixels and a width of 50%

Example

Set the height and width of a <div> element:

div {
  height: 200px;
  width: 50%;
  background-color: powderblue;
}

This element has a height of 100 pixels and a width of 500 pixels.

Example

Set the height and width of another <div> element:

div {
  height: 100px;
  width: 500px;
  background-color: powderblue;
}

Note: Remember that the height and width properties do not include padding, borders, or margins! They set the height/width of the area inside the padding, border, and margin of the element!



Setting max-width

The max-width property is used to set the maximum width of an element.

The max-width can be specified in length values, like px, cm, etc., or in percent (%) of the containing block, or set to none (this is default. Means that there is no maximum width).

The problem with the <div> above occurs when the browser window is smaller than the width of the element (500px). The browser then adds a horizontal scrollbar to the page.

Using max-width instead, in this situation, will improve the browser's handling of small windows.

Tip: Drag the browser window to smaller than 500px wide, to see the difference between the two divs!

This element has a height of 100 pixels and a max-width of 500 pixels.

Note: If you for some reason use both the width property and the max-width property on the same element, and the value of the width property is larger than the max-width property; the max-width property will be used (and the width property will be ignored).

Example

This <div> element has a height of 100 pixels and a max-width of 500 pixels: 

div {
  max-width: 500px;
  height: 100px;
  background-color: powderblue;
}

All CSS Dimension Properties

Property

Description

height

Sets the height of an element

max-height

Sets the maximum height of an element

max-width

Sets the maximum width of an element

min-height

Sets the minimum height of an element

min-width

Sets the minimum width of an element

width

Sets the width of an element

CSS Box Model

All HTML elements can be considered as boxes.

The CSS Box Model

In CSS, the term "box model" is used when talking about design and layout.

The CSS box model is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content. The image below illustrates the box model:

Explanation of the different parts:

  • Content - The content of the box, where text and images appear
  • Padding - Clears an area around the content. The padding is transparent
  • Border - A border that goes around the padding and content
  • Margin - Clears an area outside the border. The margin is transparent

The box model allows us to add a border around elements, and to define space between elements. 

Example

Demonstration of the box model:

div {
  width: 300px;
  border: 15px solid green;
  padding: 50px;
  margin: 20px;
}

Width and Height of an Element

In order to set the width and height of an element correctly in all browsers, you need to know how the box model works.

Important: When you set 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 padding, borders and margins.

Example

This <div> element will have a total width of 350px: 

div {
  width: 320px;
  padding: 10px;
  border: 5px solid gray;
  margin: 0;
}

Here is the calculation:

320px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 0px (left + right margin)
= 350px

The total width of an element should be calculated like this:

Total element width = width + left padding + right padding + left border + right border + left margin + right margin

The total height of an element should be calculated like this:

Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin

Top of Form

 

CSS Outline

An outline is a line drawn outside the element's border.

This element has a black border and a green outline with a width of 10px.

CSS Outline

An outline is a line that is drawn around elements, OUTSIDE the borders, to make the element "stand out".

CSS has the following outline properties:

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

Note: Outline differs from borders! Unlike border, the outline is drawn outside the element's border, and may overlap other content. Also, the outline is NOT a part of the element's dimensions; the element's total width and height is not affected by the width of the outline.

CSS Outline Style

The outline-style property specifies the style of the outline, and can have one of the following values:

  • dotted - Defines a dotted outline
  • dashed - Defines a dashed outline
  • solid - Defines a solid outline
  • double - Defines a double outline
  • groove - Defines a 3D grooved outline
  • ridge - Defines a 3D ridged outline
  • inset - Defines a 3D inset outline
  • outset - Defines a 3D outset outline
  • none - Defines no outline
  • hidden - Defines a hidden outline

The following example shows the different outline-style values:

Example

Demonstration of the different outline styles:

p.dotted {outline-style: dotted;}
p.dashed {outline-style: dashed;}
p.solid {outline-style: solid;}
p.double {outline-style: double;}
p.groove {outline-style: groove;}
p.ridge {outline-style: ridge;}
p.inset {outline-style: inset;}
p.outset {outline-style: outset;}

Result:

A dotted outline.

A dashed outline.

A solid outline.

A double outline.

A groove outline. The effect depends on the outline-color value.

A ridge outline. The effect depends on the outline-color value.

An inset outline. The effect depends on the outline-color value.

An outset outline. The effect depends on the outline-color value.

Note: None of the other outline properties (which you will learn more about in the next chapters) will have ANY effect unless the outline-style property is set!

CSS Outline Width

The outline-width property specifies the width of the outline, and can have one of the following values:

  • thin (typically 1px)
  • medium (typically 3px)
  • thick (typically 5px)
  • A specific size (in px, pt, cm, em, etc)

The following example shows some outlines with different widths:

A thin outline.

A medium outline.

A thick outline.

A 4px thick outline.

Example

p.ex1 {
  border: 1px solid black;
  outline-style: solid;
  outline-color: red;
  outline-width: thin;
}

p.ex2 {
  border: 1px solid black;
  outline-style: solid;
  outline-color: red;
  outline-width: medium;
}

p.ex3 {
  border: 1px solid black;
  outline-style: solid;
  outline-color: red;
  outline-width: thick;
}

p.ex4 {
  border: 1px solid black;
  outline-style: solid;
  outline-color: red;
  outline-width: 4px;

CSS Outline Color

The outline-color property is used to set the color of the outline.

The color can be set by:

  • name - specify a color name, like "red"
  • HEX - specify a hex value, like "#ff0000"
  • RGB - specify a RGB value, like "rgb(255,0,0)"
  • HSL - specify a HSL value, like "hsl(0, 100%, 50%)"
  • invert - performs a color inversion (which ensures that the outline is visible, regardless of color background)

The following example shows some different outlines with different colors. Also notice that these elements also have a thin black border inside the outline:

A solid red outline.

A dotted blue outline.

An outset grey outline.

Example

p.ex1 {
  border: 2px solid black;
  outline-style: solid;
  outline-color: red;
}

p.ex2 {
  border: 2px solid black;
  outline-style: dotted;
  outline-color: blue;
}

p.ex3 {
  border: 2px solid black;
  outline-style: outset;
  outline-color: grey;
}

HEX Values

The outline color can also be specified using a hexadecimal value (HEX):

Example

p.ex1 {
  outline-style: solid;
  outline-color: #ff0000; /* red */
}

RGB Values

Or by using RGB values:

Example

p.ex1 {
  outline-style: solid;
  outline-color: rgb(255, 0, 0); /* red */
}

HSL Values

You can also use HSL values:

Example

p.ex1 {
  outline-style: solid;
  outline-color: hsl(0, 100%, 50%); /* red */
}

CSS Outline Shorthand

CSS Outline - Shorthand property

The outline property is a shorthand property for setting the following individual outline properties:

  • outline-width
  • outline-style (required)
  • outline-color

The outline property is specified as one, two, or three values from the list above. The order of the values does not matter.

The following example shows some outlines specified with the shorthand outline property:

A dashed outline.

A dotted red outline.

A 5px solid yellow outline.

A thick ridge pink outline.

Example

p.ex1 {outline: dashed;}
p.ex2 {outline: dotted red;}
p.ex3 {outline: 5px solid yellow;}
p.ex4 {outline: thick ridge pink;}

CSS Outline Offset

The outline-offset property adds space between an outline and the edge/border of an element. The space between an element and its outline is transparent.

The following example specifies an outline 15px outside the border edge:

This paragraph has an outline 15px outside the border edge.

Example

{
  margin: 30px;
  border: 1px solid black;
  outline: 1px solid red;
  outline-offset: 15px;
}

The following example shows that the space between an element and its outline is transparent:

This paragraph has an outline of 15px outside the border edge.

Example

{
  margin: 30px;
  background: yellow;
  border: 1px solid black;
  outline: 1px solid red;
  outline-offset: 15px;
}

Bottom of Form


All CSS Outline Properties

Property

Description

outline

A shorthand property for setting outline-width, outline-style, and outline-color in one declaration

outline-color

Sets the color of an outline

outline-offset

Specifies the space between an outline and the edge or border of an element

outline-style

Sets the style of an outline

outline-width

Sets the width of an outline

 

 

CSS Text

CSS has a lot of properties for formatting text.

TEXT FORMATTING

This text is styled with some of the text formatting properties. The heading uses the text-align, text-transform, and color properties. The paragraph is indented, aligned, and the space between characters is specified. The underline is removed from this colored.

Text Color

The color property is used to set the color of the text. The color is specified by:

  • a color name - like "red"
  • a HEX value - like "#ff0000"
  • an RGB value - like "rgb(255,0,0)"

The default text color for a page is defined in the body selector.

Example

body {
  color: blue;
}

h1 {
  color: green;
}

Text Color and Background Color

In this example, we define both the background-color property and the color property:

Example

body {
  background-color: lightgrey;
  color: blue;
}

h1 {
  background-color: black;
  color: white;
}

div {
  background-color: blue;
  color: white;
}

Important: High contrast is very important for people with vision problems. So, always ensure that the contrast between the text color and the background color (or background image) is good!

The CSS Text Color Property

Property

Description

color

Specifies the color of text

CSS Fonts

Choosing the right font for your website is important!

Font Selection is Important

Choosing the right font has a huge impact on how the readers experience a website.

The right font can create a strong identity for your brand.

Using a font that is easy to read is important. The font adds value to your text. It is also important to choose the correct color and text size for the font.


Generic Font Families

In CSS there are five generic font families:

  1. Serif fonts have a small stroke at the edges of each letter. They create a sense of formality and elegance.
  2. Sans-serif fonts have clean lines (no small strokes attached). They create a modern and minimalistic look.
  3. Monospace fonts - here all the letters have the same fixed width. They create a mechanical look. 
  4. Cursive fonts imitate human handwriting.
  5. Fantasy fonts are decorative/playful fonts.

All the different font names belong to one of the generic font families. 

Difference Between Serif and Sans-serif Fonts

Serif vs. Sans-serif

Note: On computer screens, sans-serif fonts are considered easier to read than serif fonts.

Some Font Examples

Generic Font Family

Examples of Font Names

Serif

Times New Roman
Georgia
Garamond

Sans-serif

Arial
Verdana
Helvetica

Monospace

Courier New
Lucida Console
Monaco

Cursive

Brush Script MT
Lucida Handwriting

Fantasy

Copperplate
Papyrus

The CSS font-family Property

In CSS, we use the font-family property to specify the font of a text.

Note: If the font name is more than one word, it must be in quotation marks, like: "Times New Roman".

Example

Specify some different fonts for three paragraphs:

.p1 {
  font-family: "Times New Roman", Times, serif;
}

.p2 {
  font-family: Arial, Helvetica, sans-serif;
}

.p3 {
  font-family: "Lucida Console", "Courier New", monospace;

CSS Web Safe Fonts

What are Web Safe Fonts?

Web safe fonts are fonts that are universally installed across all browsers and devices.

Fallback Fonts

However, there are no 100% completely web safe fonts. There is always a chance that a font is not found or is not installed properly.

Therefore, it is very important to always use fallback fonts.

This means that you should add a list of similar "backup fonts" in the font-family property. If the first font does not work, the browser will try the next one, and the next one, and so on. Always end the list with a generic font family name.

Example

Here, there are three font types: Tahoma, Verdana, and sans-serif. The second and third fonts are backups, in case the first one is not found.

{
font-family: Tahoma, Verdana, sans-serif;
}

Best Web Safe Fonts for HTML and CSS

The following list are the best web safe fonts for HTML and CSS:

  • Arial (sans-serif)
  • Verdana (sans-serif)
  • Tahoma (sans-serif)
  • Trebuchet MS (sans-serif)
  • Times New Roman (serif)
  • Georgia (serif)
  • Garamond (serif)
  • Courier New (monospace)
  • Brush Script MT (cursive)

CSS Font Fallbacks

Commonly Used Font Fallbacks

Below are some commonly used font fallbacks, organized by the 5 generic font families:

  • Serif
  • Sans-serif
  • Monospace
  • Cursive
  • Fantasy

Serif Fonts

font-family

Example text

"Times New Roman", Times, serif

This is a Heading

This is a paragraph.

Georgia, serif

This is a Heading

This is a paragraph.

Garamond, serif

This is a Heading

This is a paragraph.

Sans-Serif Fonts

font-family

Example text

Arial, Helvetica, sans-serif

This is a Heading

This is a paragraph.

Tahoma, Verdana, sans-serif

This is a Heading

This is a paragraph.

"Trebuchet MS", Helvetica, sans-serif

This is a Heading

This is a paragraph.

Geneva, Verdana, sans-serif

This is a Heading

This is a paragraph.


Monospace Fonts

font-family

Example text

"Courier New", Courier, monospace

This is a Heading

This is a paragraph.

Cursive Fonts

font-family

Example text

"Brush Script MT", cursive

This is a Heading

This is a paragraph.

Fantasy Fonts

font-family

Example text

Copperplate, Papyrus, fantasy

This is a Heading

This is a paragraph.

Bottom of Form

All CSS Font Properties

Property

Description

font

Sets all the font properties in one declaration

font-family

Specifies the font family for text

font-size

Specifies the font size of text

font-style

Specifies the font style for text

font-variant

Specifies whether or not a text should be displayed in a small-caps font

font-weight

Specifies the weight of a font

 

 

 

 

CSS Icons

Icons can easily be added to your HTML page, by using an icon library.

How To Add Icons

The simplest way to add an icon to your HTML page, is with an icon library, such as Font Awesome.

Add the name of the specified icon class to any inline HTML element (like <i> or <span>).

All the icons in the icon libraries below, are scalable vectors that can be customized with CSS (size, color, shadow, etc.)


Font Awesome Icons

To use the Font Awesome icons, go to fontawesome.com, sign in, and get a code to add in the <head> section of your HTML page:

<script src="https://kit.fontawesome.com/yourcode.js" crossorigin="anonymous"></script>

Note: No downloading or installation is required!

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script>
</head>
<body>

<i class="fas fa-cloud"></i>
<i class="fas fa-heart"></i>
<i class="fas fa-car"></i>
<i class="fas fa-file"></i>
<i class="fas fa-bars"></i>

</body>
</html>

 

 

CSS Links

With CSS, links can be styled in many different ways.

Text Link Text Link Link Button Link Button

Styling Links

Links can be styled with any CSS property (e.g. colorfont-familybackground, etc.).

Example

{
  color: hotpink;
}

In addition, links can be styled differently depending on what state they are in.

The four links states are:

  • a:link - a normal, unvisited link
  • a:visited - a link the user has visited
  • a:hover - a link when the user mouses over it
  • a:active - a link the moment it is clicked

Example

/* unvisited link */
a:link {
  color: red;
}

/* visited link */
a:visited {
  color: green;
}

/* mouse over link */
a:hover {
  color: hotpink;
}

/* selected link */
a:active {
  color: blue;
}

When setting the style for several link states, there are some order rules:

  • a:hover MUST come after a:link and a:visited
  • a:active MUST come after a:hover

Text Decoration

The text-decoration property is mostly used to remove underlines from links:

Example

a:link {
  text-decoration: none;
}

a:visited {
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

a:active {
  text-decoration: underline;
}

Background Color

The background-color property can be used to specify a background color for links:

Example

a:link {
  background-color: yellow;
}

a:visited {
  background-color: cyan;
}

a:hover {
  background-color: lightgreen;
}

a:active {
  background-color: hotpink;
} 

Link Buttons

This example demonstrates a more advanced example where we combine several CSS properties to display links as boxes/buttons:

Example

a:link, a:visited {
  background-color: #f44336;
  color: white;
  padding: 14px 25px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
}

a:hover, a:active {
  background-color: red;
}

More Examples

Example

This example demonstrates how to add other styles to hyperlinks:

a.one:link {color: #ff0000;}
a.one:visited {color: #0000ff;}
a.one:hover {color: #ffcc00;}

a.two:link {color: #ff0000;}
a.two:visited {color: #0000ff;}
a.two:hover {font-size: 150%;}

a.three:link {color: #ff0000;}
a.three:visited {color: #0000ff;}
a.three:hover {background: #66ff66;}

a.four:link {color: #ff0000;}
a.four:visited {color: #0000ff;}
a.four:hover {font-family: monospace;}

a.five:link {color: #ff0000; text-decoration: none;}
a.five:visited {color: #0000ff; text-decoration: none;}
a.five:hover {text-decoration: underline;}

Example

Another example of how to create link boxes/buttons:

a:link, a:visited {
  background-color: white;
  color: black;
  border: 2px solid green;
  padding: 10px 20px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
}

a:hover, a:active {
  background-color: green;
  color: white;
}

This example demonstrates the different types of cursors (can be useful for links):

<span style="cursor: auto">auto</span><br>
<span style="cursor: crosshair">crosshair</span><br>
<span style="cursor: default">default</span><br>
<span style="cursor: e-resize">e-resize</span><br>
<span style="cursor: help">help</span><br>
<span style="cursor: move">move</span><br>
<span style="cursor: n-resize">n-resize</span><br>
<span style="cursor: ne-resize">ne-resize</span><br>
<span style="cursor: nw-resize">nw-resize</span><br>
<span style="cursor: pointer">pointer</span><br>
<span style="cursor: progress">progress</span><br>
<span style="cursor: s-resize">s-resize</span><br>
<span style="cursor: se-resize">se-resize</span><br>
<span style="cursor: sw-resize">sw-resize</span><br>
<span style="cursor: text">text</span><br>
<span style="cursor: w-resize">w-resize</span><br>
<span style="cursor: wait">wait</span>

CSS Lists

❮ PreviousNext ❯

Unordered Lists:

  • Coffee
  • Tea
  • Coca Cola
  • Coffee
  • Tea
  • Coca Cola

Ordered Lists:

  1. Coffee
  2. Tea
  3. Coca Cola
  1. Coffee
  2. Tea
  3. Coca Cola

HTML Lists and CSS List Properties

In HTML, there are two main types of lists:

  • unordered lists (<ul>) - the list items are marked with bullets
  • ordered lists (<ol>) - the list items are marked with numbers or letters

The CSS list properties allow you to:

  • Set different list item markers for ordered lists
  • Set different list item markers for unordered lists
  • Set an image as the list item marker
  • Add background colors to lists and list items

Different List Item Markers

The list-style-type property specifies the type of list item marker.

The following example shows some of the available list item markers:

Example

ul.a {
  list-style-type: circle;
}

ul.b {
  list-style-type: square;
}

ol.c {
  list-style-type: upper-roman;
}

ol.d {
  list-style-type: lower-alpha;
}

Note: Some of the values are for unordered lists, and some for ordered lists.

An Image as The List Item Marker

The list-style-image property specifies an image as the list item marker:

Example

ul {
  list-style-image: url('sqpurple.gif');
}

Position The List Item Markers

The list-style-position property specifies the position of the list-item markers (bullet points).

"list-style-position: outside;" means that the bullet points will be outside the list item. The start of each line of a list item will be aligned vertically. This is default:

  • Coffee - A brewed drink prepared from roasted coffee beans...
  • Tea
  • Coca-cola

"list-style-position: inside;" means that the bullet points will be inside the list item. As it is part of the list item, it will be part of the text and push the text at the start:

  • Coffee - A brewed drink prepared from roasted coffee beans...
  • Tea
  • Coca-cola

Example

ul.a {
  list-style-position: outside;
}

ul.b {
  list-style-position: inside;
}

Remove Default Settings

The list-style-type:none property can also be used to remove the markers/bullets. Note that the list also has default margin and padding. To remove this, add margin:0 and padding:0 to <ul> or <ol>:

Example

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

List - Shorthand property

The list-style property is a shorthand property. It is used to set all the list properties in one declaration:

Example

ul {
  list-style: square inside url("sqpurple.gif");
}

When using the shorthand property, the order of the property values are:

  • list-style-type (if a list-style-image is specified, the value of this property will be displayed if the image for some reason cannot be displayed)
  • list-style-position (specifies whether the list-item markers should appear inside or outside the content flow)
  • list-style-image (specifies an image as the list item marker)

If one of the property values above is missing, the default value for the missing property will be inserted, if any.

Styling List With Colors

We can also style lists with colors, to make them look a little more interesting.

Anything added to the <ol> or <ul> tag, affects the entire list, while properties added to the <li> tag will affect the individual list items:

Example

ol {
  background: #ff9999;
  padding: 20px;
}

ul {
  background: #3399ff;
  padding: 20px;
}

ol li {
  background: #ffe5e5;
  color: darkred;
  padding: 5px;
  margin-left: 35px;
}

ul li {
  background: #cce5ff;
  color: darkblue;
  margin: 5px;
}

Result:

1.   Coffee

2.   Tea

3.   Coca Cola

·         Coffee

·         Tea

·         Coca Cola

 

Bottom of Form

All CSS List Properties

Property

Description

list-style

Sets all the properties for a list in one declaration

list-style-image

Specifies an image as the list-item marker

list-style-position

Specifies the position of the list-item markers (bullet points)

list-style-type

Specifies the type of list-item marker

CSS Tables

Table Borders

To specify table borders in CSS, use the border property.

The example below specifies a solid border for <table>, <th>, and <td> elements:

Firstname

Lastname

Name

Name

Example

table, th, td {
  border: 1px solid;
}

Full-Width Table

The table above might seem small in some cases. If you need a table that should span the entire screen (full-width), add width: 100% to the <table> element:

Firstname

Lastname

Example

table {
  width: 100%;
}

Double Borders

Notice that the table in the examples above have double borders. This is because both the table and the <th> and <td> elements have separate borders.

To remove double borders, take a look at the example below.

Collapse Table Borders

The border-collapse property sets whether the table borders should be collapsed into a single border:

Firstname

Lastname

Example

table {
  border-collapse: collapse;
}

If you only want a border around the table, only specify the border property for <table>:

Firstname

Lastname

Example

table {
  border: 1px solid;
}

CSS Table Size

Table Width and Height

The width and height of a table are defined by the width and height properties.

The example below sets the width of the table to 100%, and the height of the <th> elements to 70px:

Firstname

Lastname

Savings

Example

table {
  width: 100%;
}

th {
  height: 70px;
}

To create a table that should only span half the page, use width: 50%:

Firstname

Lastname

Savings

Name

Name

Name

Example

table {
  width: 50%;
}

CSS Table Alignment

Horizontal Alignment

The text-align property sets the horizontal alignment (like left, right, or center) of the content in <th> or <td>.

By default, the content of <th> elements are center-aligned and the content of <td> elements are left-aligned.

To center-align the content of  <td> elements as well, use text-align: center:

Firstname

Lastname

Savings

Name

Name

Name

Example

td {
  text-align: center;
}

To left-align the content, force the alignment of <th> elements to be left-aligned, with the text-align: left property:

Firstname

Lastname

Savings

Name

Name

Name

Example

th {
  text-align: left;
}

Vertical Alignment

The vertical-align property sets the vertical alignment (like top, bottom, or middle) of the content in <th> or <td>.

By default, the vertical alignment of the content in a table is middle (for both <th> and <td> elements).

The following example sets the vertical text alignment to bottom for <td> elements:

Firstname

Lastname

Savings

Name

Name

Name

Example

td {
  height: 50px;
  vertical-align: bottom;
}

CSS Table Alignment

Horizontal Alignment

The text-align property sets the horizontal alignment (like left, right, or center) of the content in <th> or <td>.

By default, the content of <th> elements are center-aligned and the content of <td> elements are left-aligned.

To center-align the content of  <td> elements as well, use text-align: center:

Firstname

Lastname

Savings

Name

Name

Name

Example

td {
  text-align: center;
}

To left-align the content, force the alignment of <th> elements to be left-aligned, with the text-align: left property:

Firstname

Lastname

Savings

Name

Name

Name

Example

th {
  text-align: left;
}

Vertical Alignment

The vertical-align property sets the vertical alignment (like top, bottom, or middle) of the content in <th> or <td>.

By default, the vertical alignment of the content in a table is middle (for both <th> and <td> elements).

The following example sets the vertical text alignment to bottom for <td> elements:

Firstname

Lastname

Savings

Name

Name

Name

Example

td {
  height: 50px;
  vertical-align: bottom;
}

CSS Responsive Table

Responsive Table

A responsive table will display a horizontal scroll bar if the screen is too small to display the full content:

 

First Name

Last Name

Points

Points

Points

Points

Points

Points

Points

Points

Points

Name

Name

00

00

00

00

00

00

00

00

00

Name

Name

00

00

00

00

00

00

00

00

00

Name

Name

00

00

00

00

00

00

00

00

00

Add a container element (like <div>) with overflow-x:auto around the <table> element to make it responsive:

Example

<div style="overflow-x:auto;">

<table>
... table content ...
</table>

</div>

Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown when being used (even though "overflow:scroll" is set).

Bottom of Form


CSS Table Properties

Property

Description

border

Sets all the border properties in one declaration

border-collapse

Specifies whether or not table borders should be collapsed

border-spacing

Specifies the distance between the borders of adjacent cells

caption-side

Specifies the placement of a table caption

empty-cells

Specifies whether or not to display borders and background on empty cells in a table

table-layout

Sets the layout algorithm to be used for a table

 

CSS Layout - The display Property

The display property is the most important CSS property for controlling layout.

The display Property

The display property specifies if/how an element is displayed.

Every HTML element has a default display value depending on what type of element it is. The default display value for most elements is block or inline.

Click to show panel

Block-level Elements

A block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).

The <div> element is a block-level element.

Examples of block-level elements:

  • <div>
  • <h1> - <h6>
  • <p>
  • <form>
  • <header>
  • <footer>
  • <section>

Inline Elements

An inline element does not start on a new line and only takes up as much width as necessary.

This is an inline <span> element inside a paragraph.

Examples of inline elements:

  • <span>
  • <a>
  • <img>

Display: none;

display: none; is commonly used with JavaScript to hide and show elements without deleting and recreating them. Take a look at our last example on this page if you want to know how this can be achieved.

The <script> element uses display: none; as default. 

Override The Default Display Value

As mentioned, every element has a default display value. However, you can override this.

Changing an inline element to a block element, or vice versa, can be useful for making the page look a specific way, and still follow the web standards.

A common example is making inline <li> elements for horizontal menus:

Example

li {
  display: inline;
}

Note: Setting the display property of an element only changes how the element is displayed, NOT what kind of element it is. So, an inline element with display: block; is not allowed to have other block elements inside it.

The following example displays <span> elements as block elements:

Example

span {
  display: block;
}

The following example displays <a> elements as block elements:

Example

{
  display: block;
}

Hide an Element - display:none or visibility:hidden?

display:none

Italy

Remove

visibility:hidden

Forest

Hide

Reset

Lights

Reset All

Hiding an element can be done by setting the display property to none. The element will be hidden, and the page will be displayed as if the element is not there:

Example

h1.hidden {
  display: none;
}

visibility:hidden; also hides an element.

However, the element will still take up the same space as before. The element will be hidden, but still affect the layout:

Example

h1.hidden {
  visibility: hidden;
}

Bottom of Form


CSS Display/Visibility Properties

Property

Description

display

Specifies how an element should be displayed

visibility

Specifies whether or not an element should be visible

CSS Layout - width and max-width

❮ PreviousNext ❯

Using width, max-width and margin: auto;

As mentioned in the previous chapter; a block-level element always takes up the full width available (stretches out to the left and right as far as it can).

Setting the width of a block-level element will prevent it from stretching out to the edges of its container. Then, you can set the margins to auto, to horizontally center the element within its container. The element will take up the specified width, and the remaining space will be split equally between the two margins:

This <div> element has a width of 500px, and margin set to auto.



Note: The problem with the <div> above occurs when the browser window is smaller than the width of the element. The browser then adds a horizontal scrollbar to the page.

Using max-width instead, in this situation, will improve the browser's handling of small windows. This is important when making a site usable on small devices:

This <div> element has a max-width of 500px, and margin set to auto.


Tip: Resize the browser window to less than 500px wide, to see the difference between the two divs!

Here is an example of the two divs above:

Example

div.ex1 {
  width: 500px;
  margin: auto;
  border: 3px solid #73AD21;
}

div.ex2 {
  max-width: 500px;
  margin: auto;
  border: 3px solid #73AD21;
}

CSS Layout - The position Property

❮ PreviousNext ❯


The position property specifies the type of positioning method used for an element (static, relative, fixed, absolute or sticky).


The position Property

The position property specifies the type of positioning method used for an element.

There are five different position values:

  • static
  • relative
  • fixed
  • absolute
  • sticky

Elements are then positioned using the top, bottom, left, and right properties. However, these properties will not work unless the position property is set first. They also work differently depending on the position value.


position: static;

HTML elements are positioned static by default.

Static positioned elements are not affected by the top, bottom, left, and right properties.

An element with position: static; is not positioned in any special way; it is always positioned according to the normal flow of the page:

This <div> element has position: static;

Here is the CSS that is used:

Example

div.static {
  position: static;
  border: 3px solid #73AD21;
}

position: relative;

An element with position: relative; is positioned relative to its normal position.

Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element.

This <div> element has position: relative;

Here is the CSS that is used:

Example

div.relative {
  position: relative;
  left: 30px;
  border: 3px solid #73AD21;
}


position: fixed;

An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element.

A fixed element does not leave a gap in the page where it would normally have been located.

Notice the fixed element in the lower-right corner of the page. Here is the CSS that is used:

Example

div.fixed {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 300px;
  border: 3px solid #73AD21;
}

This <div> element has position: fixed;

position: absolute;

An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).

However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.

Here is a simple example:

This <div> element has position: relative;

This <div> element has position: absolute;

Here is the CSS that is used:

Example

div.relative {
  position: relative;
  width: 400px;
  height: 200px;
  border: 3px solid #73AD21;
}

div.absolute {
  position: absolute;
  top: 80px;
  right: 0;
  width: 200px;
  height: 100px;
  border: 3px solid #73AD21;
}

position: sticky;

An element with position: sticky; is positioned based on the user's scroll position.

A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).

Note: Internet Explorer does not support sticky positioning. Safari requires a -webkit- prefix (see example below). You must also specify at least one of toprightbottom or left for sticky positioning to work.

In this example, the sticky element sticks to the top of the page (top: 0), when you reach its scroll position.

Example

div.sticky {
  position: -webkit-sticky; /* Safari */
  position: sticky;
  top: 0;
  background-color: green;
  border: 2px solid #4CAF50;
}

Positioning Text In an Image

How to position text over an image:

Example

Cinque Terre

Bottom Left

Top Left

Top Right

Bottom Right

Centered

 

All CSS Positioning Properties

Property

Description

bottom

Sets the bottom margin edge for a positioned box

clip

Clips an absolutely positioned element

left

Sets the left margin edge for a positioned box

position

Specifies the type of positioning for an element

right

Sets the right margin edge for a positioned box

top

Sets the top margin edge for a positioned box

 

CSS Layout - The z-index Property

The z-index property specifies the stack order of an element.

The z-index Property

When elements are positioned, they can overlap other elements.

The z-index property specifies the stack order of an element (which element should be placed in front of, or behind, the others).

An element can have a positive or negative stack order:

This is a heading

https://www.w3schools.com/css/img_tree.png

Because the image has a z-index of -1, it will be placed behind the text.

Example

img {
  position: absolute;
  left: 0px;
  top: 0px;
  z-index: -1;
}

Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display: flex elements).

Another z-index Example

Example

Here we see that an element with greater stack order is always above an element with a lower stack order:

<html>
<head>
<style>
.container {
  position: relative;
}

.black-box {
  position: relative;
  z-index: 1;
  border: 2px solid black;
  height: 100px;
  margin: 30px;
}

.gray-box {
  position: absolute;
  z-index: 3;
  background: lightgray;
  height: 60px;
  width: 70%;
  left: 50px;
  top: 50px;
}

.green-box {
  position: absolute;
  z-index: 2;
  background: lightgreen;
  width: 35%;
  left: 270px;
  top: -15px;
  height: 100px;
}
</style>
</head>
<body>

<div class="container">
  
<div class="black-box">Black box</div>
  
<div class="gray-box">Gray box</div>
  
<div class="green-box">Green box</div>
</div>

</body>
</html>

Without z-index

If two positioned elements overlap each other without a z-index specified, the element defined last in the HTML code will be shown on top.

Example

Same example as above, but here with no z-index specified:

<html>
<head>
<style>
.container {
  position: relative;
}

.black-box {
  position: relative;
  border: 2px solid black;
  height: 100px;
  margin: 30px;
}

.gray-box {
  position: absolute;
  background: lightgray;
  height: 60px;
  width: 70%;
  left: 50px;
  top: 50px;
}

.green-box {
  position: absolute;
  background: lightgreen;
  width: 35%;
  left: 270px;
  top: -15px;
  height: 100px;
}
</style>
</head>
<body>

<div class="container">
  
<div class="black-box">Black box</div>
  
<div class="gray-box">Gray box</div>
  
<div class="green-box">Green box</div>
</div>

</body>
</html>

Top of Form

Bottom of Form

 CSS Property

Property

Description

z-index

Sets the stack order of an element

CSS Layout - float and clear

The CSS float property specifies how an element should float.

The CSS clear property specifies what elements can float beside the cleared element and on which side.

The float Property

The float property is used for positioning and formatting content e.g. let an image float left to the text in a container.

The float property can have one of the following values:

  • left - The element floats to the left of its container
  • right - The element floats to the right of its container
  • none - The element does not float (will be displayed just where it occurs in the text). This is default
  • inherit - The element inherits the float value of its parent

In its simplest use, the float property can be used to wrap text around images.

Example - float: right;

The following example specifies that an image should float to the right in a text:

PineappleLorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac...

Example

img {
  float: right;
}

Example - float: left;

The following example specifies that an image should float to the left in a text:

PineappleLorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac...

Example

img {
  float: left;
}

Example - No float

In the following example the image will be displayed just where it occurs in the text (float: none;):

Pineapple Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac...

Example

img {
  float: none;
}

Example - Float Next To Each Other

Normally div elements will be displayed on top of each other. However, if we use float: left we can let elements float next to each other:

Example

div {
  float: left;
  padding: 15px;
}

.div1 {
  background: red;
}

.div2 {
  background: yellow;
}

.div3 {
  background: green;
}

CSS Layout - display: inline-block

The display: inline-block Value

Compared to display: inline, the major difference is that display: inline-block allows to set a width and height on the element.

Also, with display: inline-block, the top and bottom margins/paddings are respected, but with display: inline they are not.

Compared to display: block, the major difference is that display: inline-block does not add a line-break after the element, so the element can sit next to other elements.

The following example shows the different behavior of display: inlinedisplay: inline-block and display: block:

Example

span.a {
  display: inline; /* the default for span */
  width: 100px;
  height: 100px;
  padding: 5px;
  border: 1px solid blue;
  background-color: yellow;
}

span.b {
  display: inline-block;
  width: 100px;
  height: 100px;
  padding: 5px;
  border: 1px solid blue;
  background-color: yellow;
}

span.c {
  display: block;
  width: 100px;
  height: 100px;
  padding: 5px;
  border: 1px solid blue;
  background-color: yellow;
}

Using inline-block to Create Navigation Links

One common use for display: inline-block is to display list items horizontally instead of vertically. The following example creates horizontal navigation links:

Example

.nav {
  background-color: yellow;
  list-style-type: none;
  text-align: center; 
  padding: 0;
  margin: 0;
}

.nav li {
  display: inline-block;
  font-size: 20px;
  padding: 20px;
}

CSS Layout - Horizontal & Vertical Align

❮ PreviousNext ❯

 

▲▼

Center elements
horizontally and vertically

Center Align Elements

To horizontally center a block element (like <div>), use margin: auto;

Setting the width of the element will prevent it from stretching out to the edges of its container.

The element will then take up the specified width, and the remaining space will be split equally between the two margins:

This div element is centered.

Example

.center {
  margin: auto;
  width: 50%;
  border: 3px solid green;
  padding: 10px;
}

Note: Center aligning has no effect if the width property is not set (or set to 100%).

Center Align Text

To just center the text inside an element, use text-align: center;

This text is centered.

Example

.center {
  text-align: center;
  border: 3px solid green;
}

 

Center an Image

To center an image, set left and right margin to auto and make it into a block element:

Paris

Example

img {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 40%;
}

Left and Right Align - Using position

One method for aligning elements is to use position: absolute;:

In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.

Example

.right {
  position: absolute;
  right: 0px;
  width: 300px;
  border: 3px solid #73AD21;
  padding: 10px;
}

Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.


Left and Right Align - Using float

Another method for aligning elements is to use the float property:

Example

.right {
  float: right;
  width: 300px;
  border: 3px solid #73AD21;
  padding: 10px;
}

The clearfix Hack

Note: If an element is taller than the element containing it, and it is floated, it will overflow outside of its container. You can use the "clearfix hack" to fix this (see example below).

Without Clearfix

https://www.w3schools.com/howto/clearfix_prob.jpg

With Clearfix

https://www.w3schools.com/howto/clearfix_solution.jpg

Then we can add the clearfix hack to the containing element to fix this problem:

Example

.clearfix::after {
  content: "";
  clear: both;
  display: table;
}

Center Vertically - Using padding

There are many ways to center an element vertically in CSS. A simple solution is to use top and bottom padding:

I am vertically centered.

Example

.center {
  padding: 70px 0;
  border: 3px solid green;
}

To center both vertically and horizontally, use padding and text-align: center:

I am vertically and horizontally centered.

Example

.center {
  padding: 70px 0;
  border: 3px solid green;
  text-align: center;
}

Center Vertically - Using line-height

Another trick is to use the line-height property with a value that is equal to the height property:

I am vertically and horizontally centered.

Example

.center {
  line-height: 200px;
  height: 200px;
  border: 3px solid green;
  text-align: center;
}

/* If the text has multiple lines, add the following: */
.center p {
  line-height: 1.5;
  display: inline-block;
  vertical-align: middle;
}

Center Vertically - Using position & transform

If padding and line-height are not options, another solution is to use positioning and the transform property:

I am vertically and horizontally centered.

Example

.center {
  height: 200px;
  position: relative;
  border: 3px solid green;
}

.center p {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Center Vertically - Using Flexbox

You can also use flexbox to center things. Just note that flexbox is not supported in IE10 and earlier versions:

I am vertically and horizontally centered.

Example

.center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  border: 3px solid green;
}

Top of Form

CSS Combinators

❮ PreviousNext ❯

A combinator is something that explains the relationship between the selectors.

A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.

There are four different combinators in CSS:

  • descendant selector (space)
  • child selector (>)
  • adjacent sibling selector (+)
  • general sibling selector (~)

Descendant Selector

The descendant selector matches all elements that are descendants of a specified element.

The following example selects all <p> elements inside <div> elements: 

Example

div p {
  background-color: yellow;
}

Child Selector (>)

The child selector selects all elements that are the children of a specified element.

The following example selects all <p> elements that are children of a <div> element:

Example

div > p {
  background-color: yellow;
}

Adjacent Sibling Selector (+)

The adjacent sibling selector is used to select an element that is directly after another specific element.

Sibling elements must have the same parent element, and "adjacent" means "immediately following".

The following example selects the first <p> element that are placed immediately after <div> elements:

Example

div + p {
  background-color: yellow;
}

General Sibling Selector (~)

The general sibling selector selects all elements that are next siblings of a specified element.

The following example selects all <p> elements that are next siblings of <div> elements: 

Example

div ~ p {
  background-color: yellow;
}

All CSS Combinator Selectors

Selector

Example

Example description

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 the first <p> element that are placed immediately after <div> elements

element1~element2

p ~ ul

Selects every <ul> element that are preceded by a <p> element

❮ PreviousNext ❯

CSS Pseudo-elements

What are Pseudo-Elements?

A CSS pseudo-element is used to style specified parts of an element.

For example, it can be used to:

  • Style the first letter, or line, of an element
  • Insert content before, or after, the content of an element

Syntax

The syntax of pseudo-elements:

selector::pseudo-element {
  property: value;
}

The ::first-line Pseudo-element

The ::first-line pseudo-element is used to add a special style to the first line of a text.

The following example formats the first line of the text in all <p> elements:

Example 

p::first-line {
  color: #ff0000;
  font-variant: small-caps;
}

Note: The ::first-line pseudo-element can only be applied to block-level elements.

The following properties apply to the ::first-line pseudo-element:

  • font properties
  • color properties
  • background properties
  • word-spacing
  • letter-spacing
  • text-decoration
  • vertical-align
  • text-transform
  • line-height
  • clear

Notice the double colon notation - ::first-line versus :first-line

The double colon replaced the single-colon notation for pseudo-elements in CSS3. This was an attempt from W3C to distinguish between 
pseudo-classes and pseudo-elements.

The single-colon syntax was used for both pseudo-classes and pseudo-elements in CSS2 and CSS1.

For backward compatibility, the single-colon syntax is acceptable for CSS2 and CSS1 pseudo-elements.

The ::first-letter Pseudo-element

The ::first-letter pseudo-element is used to add a special style to the first letter of a text.

The following example formats the first letter of the text in all <p> elements: 

Example

p::first-letter {
  color: #ff0000;
  font-size: xx-large;
}

Note: The ::first-letter pseudo-element can only be applied to block-level elements.

The following properties apply to the ::first-letter pseudo- element: 

  • font properties
  • color properties 
  • background properties
  • margin properties
  • padding properties
  • border properties
  • text-decoration
  • vertical-align (only if "float" is "none")
  • text-transform
  • line-height
  • float
  • clear

Pseudo-elements and HTML Classes

Pseudo-elements can be combined with HTML classes: 

Example

p.intro::first-letter {
  color: #ff0000;
  font-size: 200%;
}

The example above will display the first letter of paragraphs with class="intro", in red and in a larger size.

Multiple Pseudo-elements

Several pseudo-elements can also be combined.

In the following example, the first letter of a paragraph will be red, in an xx-large font size. The rest of the first line will be blue, and in small-caps. The rest of the paragraph will be the default font size and color:

Example

p::first-letter {
  color: #ff0000;
  font-size: xx-large;
}

p::first-line {
  color: #0000ff;
  font-variant: small-caps;
}

CSS - The ::before Pseudo-element

The ::before pseudo-element can be used to insert some content before the content of an element.

The following example inserts an image before the content of each <h1> element:

Example

h1::before {
  content: url(smiley.gif);
}

CSS - The ::after Pseudo-element

The ::after pseudo-element can be used to insert some content after the content of an element.

The following example inserts an image after the content of each <h1> element:

Example

h1::after {
  content: url(smiley.gif);
}

CSS - The ::marker Pseudo-element

The ::marker pseudo-element selects the markers of list items.

The following example styles the markers of list items:

Example

::marker {
  color: red;
  font-size: 23px;
}

CSS - The ::selection Pseudo-element

The ::selection pseudo-element matches the portion of an element that is selected by a user.

The following CSS properties can be applied to ::selectioncolorbackgroundcursor, and outline.

The following example makes the selected text red on a yellow background:

Example

::selection {
  color: red;
  background: yellow;
}

Bottom of Form


All CSS Pseudo Elements

Selector

Example

Example description

::after

p::after

Insert something after the content of each <p> element

::before

p::before

Insert something before the content of each <p> element

::first-letter

p::first-letter

Selects the first letter of each <p> element

::first-line

p::first-line

Selects the first line of each <p> element

::marker

::marker

Selects the markers of list items

::selection

p::selection

Selects the portion of an element that is selected by a user

All CSS Pseudo Classes

Selector

Example

Example description

:active

a:active

Selects the active link

: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

:enabled

input:enabled

Selects every enabled <input> element

:first-child

p:first-child

Selects every <p> elements that is the first child of its parent

: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 that 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 value starting with "it"

:last-child

p:last-child

Selects every <p> elements 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 a "readonly" attribute specified

:read-write

input:read-write

Selects <input> elements with no "readonly" attribute

:required

input:required

Selects <input> elements with a "required" attribute specified

:root

root

Selects the document's root element

: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

CSS Opacity / Transparency

The opacity property specifies the opacity/transparency of an element.

Transparent Image

The opacity property can take a value from 0.0 - 1.0. The lower the value, the more transparent:

Forest

opacity 0.2

Forest

opacity 0.5

Forest

opacity 1
(default)

Example

img {
  opacity: 0.5;
}

 

CSS Navigation Bar

Demo: Navigation Bars

Vertical

·         Home

·         News

·         Contact

·         About

Horizontal

·         Home

·         News

·         Contact

·         About



·         Home

·         News

·         Contact

·         About

Navigation Bars

Having easy-to-use navigation is important for any web site.

With CSS you can transform boring HTML menus into good-looking navigation bars.

Navigation Bar = List of Links

A navigation bar needs standard HTML as a base.

In our examples we will build the navigation bar from a standard HTML list.

A navigation bar is basically a list of links, so using the <ul> and <li> elements makes perfect sense:

Example

<ul>
  
<li><a href="default.asp">Home</a></li>
  
<li><a href="news.asp">News</a></li>
  
<li><a href="contact.asp">Contact</a></li>
  
<li><a href="about.asp">About</a></li>
</ul>

Now let's remove the bullets and the margins and padding from the list:

Example

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

Example explained:

  • list-style-type: none; - Removes the bullets. A navigation bar does not need list markers
  • Set margin: 0; and padding: 0; to remove browser default settings

The code in the example above is the standard code used in both vertical, and horizontal navigation bars, which you will learn more about in the next chapters.

CSS Vertical Navigation Bar

Vertical Navigation Bar

·         Home

·         News

·         Contact

·         About

To build a vertical navigation bar, you can style the <a> elements inside the list, in addition to the code from the previous page:

Example

li a {
  display: block;
  width: 60px;
}

Example explained:

  • display: block; - Displaying the links as block elements makes the whole link area clickable (not just the text), and it allows us to specify the width (and padding, margin, height, etc. if you want)
  • width: 60px; - Block elements take up the full width available by default. We want to specify a 60 pixels width

You can also set the width of <ul>, and remove the width of <a>, as they will take up the full width available when displayed as block elements. This will produce the same result as our previous example:

Example

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 60px;
}

li a {
  display: block;
}

Vertical Navigation Bar Examples

Create a basic vertical navigation bar with a gray background color and change the background color of the links when the user moves the mouse over them:

·         Home

·         News

·         Contact

·         About

Example

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 200px;
  background-color: #f1f1f1;
}

li a {
  display: block;
  color: #000;
  padding: 8px 16px;
  text-decoration: none;
}

/* Change the link color on hover */
li a:hover {
  background-color: #555;
  color: white;
}

Active/Current Navigation Link

Add an "active" class to the current link to let the user know which page he/she is on:

·         Home

·         News

·         Contact

·         About

Example

.active {
  background-color: #04AA6D;
  color: white;
}

Gray Horizontal Navbar

An example of a gray horizontal navigation bar with a thin gray border:

·         Home

·         News

·         Contact

·         About

Example

ul {
  border: 1px solid #e7e7e7;
  background-color: #f3f3f3;
}

li a {
  color: #666;
}

CSS Dropdowns


Create a hoverable dropdown with CSS.


 

Basic Dropdown

Create a dropdown box that appears when the user moves the mouse over an element.

Example

<style>
.dropdown 
{
  position
: relative;
  display
: inline-block;
}

.dropdown-content 
{
  display
: none;
  position
: absolute;
  background-color
: #f9f9f9;
  min-width
: 160px;
  box-shadow
: 0px 8px 16px 0px rgba(0,0,0,0.2);
  padding
: 12px 16px;
  z-index
: 1;
}

.dropdown:hover .dropdown-content 
{
  display
: block;
}
</style>

<div class="dropdown">
  
<span>Mouse over me</span>
  
<div class="dropdown-content">
    
<p>Hello World!</p>
  
</div>
</div>

Example Explained

HTML) Use any element to open the dropdown content, e.g. a <span>, or a <button> element.

Use a container element (like <div>) to create the dropdown content and add whatever you want inside of it.

Wrap a <div> element around the elements to position the dropdown content correctly with CSS.

CSS) The .dropdown class uses position:relative, which is needed when we want the dropdown content to be placed right below the dropdown button (using position:absolute).

The .dropdown-content class holds the actual dropdown content. It is hidden by default, and will be displayed on hover (see below). Note the min-width is set to 160px. Feel free to change this. Tip: If you want the width of the dropdown content to be as wide as the dropdown button, set the width to 100% (and overflow:auto to enable scroll on small screens).

Instead of using a border, we have used the CSS box-shadow property to make the dropdown menu look like a "card".

The :hover selector is used to show the dropdown menu when the user moves the mouse over the dropdown button.

Dropdown Menu

Create a dropdown menu that allows the user to choose an option from a list:

Dropdown Menu

This example is similar to the previous one, except that we add links inside the dropdown box and style them to fit a styled dropdown button:

Example

<style>
/* Style The Dropdown Button */
.dropbtn 
{
  background-color
: #4CAF50;
  color
: white;
  padding
: 16px;
  font-size
: 16px;
  border
: none;
  cursor
: pointer;
}

/* The container <div> - needed to position the dropdown content */
.dropdown 
{
  position
: relative;
  display
: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content 
{
  display
: none;
  position
: absolute;
  background-color
: #f9f9f9;
  min-width
: 160px;
  box-shadow
: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index
: 1;
}

/* Links inside the dropdown */
.dropdown-content a 
{
  color
: black;
  padding
: 12px 16px;
  text-decoration
: none;
  display
: block;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover 
{background-color: #f1f1f1}

/* Show the dropdown menu on hover */
.dropdown:hover .dropdown-content 
{
  display
: block;
}

/* Change the background color of the dropdown button when the dropdown content is shown */
.dropdown:hover .dropbtn 
{
  background-color
: #3e8e41;
}
</style>

<div class="dropdown">
  
<button class="dropbtn">Dropdown</button>
  
<div class="dropdown-content">
    
<a href="#">Link 1</a>
    
<a href="#">Link 2</a>
    
<a href="#">Link 3</a>
  
</div>
</div>

CSS Image Gallery

CSS can be used to create an image gallery.

Cinque Terre

Add a description of the image here

Forest

Add a description of the image here

Northern Lights

Add a description of the image here

Mountains

Add a description of the image here


Image Gallery

The following image gallery is created with CSS:

Example

<html>
<head>
<style>
div.gallery {
  margin: 5px;
  border: 1px solid #ccc;
  float: left;
  width: 180px;
}

div.gallery:hover {
  border: 1px solid #777;
}

div.gallery img {
  width: 100%;
  height: auto;
}

div.desc {
  padding: 15px;
  text-align: center;
}
</style>
</head>
<body>

<div class="gallery">
  
<a target="_blank" href="img_5terre.jpg">
    
<img src="img_5terre.jpg" alt="Cinque Terre" width="600" height="400">
  
</a>
  
<div class="desc">Add a description of the image here</div>
</div>

<div class="gallery">
  
<a target="_blank" href="img_forest.jpg">
    
<img src="img_forest.jpg" alt="Forest" width="600" height="400">
  
</a>
  
<div class="desc">Add a description of the image here</div>
</div>

<div class="gallery">
  
<a target="_blank" href="img_lights.jpg">
    
<img src="img_lights.jpg" alt="Northern Lights" width="600" height="400">
  
</a>
  
<div class="desc">Add a description of the image here</div>
</div>

<div class="gallery">
  
<a target="_blank" href="img_mountains.jpg">
    
<img src="img_mountains.jpg" alt="Mountains" width="600" height="400">
  
</a>
  
<div class="desc">Add a description of the image here</div>
</div>

</body>
</html>

CSS Image Sprites

❮ PreviousNext ❯

Image Sprites

An image sprite is a collection of images put into a single image.

A web page with many images can take a long time to load and generates multiple server requests.

Using image sprites will reduce the number of server requests and save bandwidth.


Image Sprites - Simple Example

Instead of using three separate images, we use this single image ("img_navsprites.gif"):

navigation images

With CSS, we can show just the part of the image we need.

In the following example the CSS specifies which part of the "img_navsprites.gif" image to show:

Example

#home {
  width: 46px;
  height: 44px;
  background: url(img_navsprites.gif) 0 0;
}

Example explained:

  • <img id="home" src="img_trans.gif"> - Only defines a small transparent image because the src attribute cannot be empty. The displayed image will be the background image we specify in CSS
  • width: 46px; height: 44px; - Defines the portion of the image we want to use
  • background: url(img_navsprites.gif) 0 0; - Defines the background image and its position (left 0px, top 0px)

This is the easiest way to use image sprites, now we want to expand it by using links and hover effects.

Image Sprites - Create a Navigation List

We want to use the sprite image ("img_navsprites.gif") to create a navigation list.

We will use an HTML list, because it can be a link and also supports a background image:

Example

#navlist {
  position: relative;
}

#navlist li {
  margin: 0;
  padding: 0;
  list-style: none;
  position: absolute;
  top: 0;
}

#navlist li, #navlist a {
  height: 44px;
  display: block;
}

#home {
  left: 0px;
  width: 46px;
  background: url('img_navsprites.gif') 0 0;
}

#prev {
  left: 63px;
  width: 43px;
  background: url('img_navsprites.gif') -47px 0;
}

#next {
  left: 129px;
  width: 43px;
  background: url('img_navsprites.gif') -91px 0;
}

Example explained:

  • #navlist {position:relative;} - position is set to relative to allow absolute positioning inside it
  • #navlist li {margin:0;padding:0;list-style:none;position:absolute;top:0;} - margin and padding are set to 0, list-style is removed, and all list items are absolute positioned
  • #navlist li, #navlist a {height:44px;display:block;} - the height of all the images is 44px

Now start to position and style for each specific part:

  • #home {left:0px;width:46px;} - Positioned all the way to the left, and the width of the image is 46px
  • #home {background:url(img_navsprites.gif) 0 0;} - Defines the background image and its position (left 0px, top 0px)
  • #prev {left:63px;width:43px;} - Positioned 63px to the right (#home width 46px + some extra space between items), and the width is 43px
  • #prev {background:url('img_navsprites.gif') -47px 0;} - Defines the background image 47px to the right (#home width 46px + 1px line divider)
  • #next {left:129px;width:43px;} - Positioned 129px to the right (start of #prev is 63px + #prev width 43px + extra space), and the width is 43px
  • #next {background:url('img_navsprites.gif') -91px 0;} - Defines the background image 91px to the right (#home width 46px + 1px line divider + #prev width 43px + 1px line divider)

Image Sprites - Hover Effect

Now we want to add a hover effect to our navigation list.

Tip: The :hover selector can be used on all elements, not only on links.

Our new image ("img_navsprites_hover.gif") contains three navigation images and three images to use for hover effects:

navigation images

Because this is one single image, and not six separate files, there will be no loading delay when a user hovers over the image.

We only add three lines of code to add the hover effect:

Example

#home a:hover {
  background: url('img_navsprites_hover.gif') 0 -45px;
}

#prev a:hover {
  background: url('img_navsprites_hover.gif') -47px -45px;
}

#next a:hover {
  background: url('img_navsprites_hover.gif') -91px -45px;
}

Example explained:

  • #home a:hover {background: url('img_navsprites_hover.gif') 0 -45px;} - For all three hover images we specify the same background position, only 45px further down

CSS Forms

3`The look of an HTML form can be greatly improved with CSS:

Top of Form

First Name  Last Name  Country               Try it Yourself »

Bottom of Form

Styling Input Fields

Use the width property to determine the width of the input field:

First Name 

Example

input {
  width: 100%;
}

The example above applies to all <input> elements. If you only want to style a specific input type, you can use attribute selectors:

  • input[type=text] - will only select text fields
  • input[type=password] - will only select password fields
  • input[type=number] - will only select number fields
  • etc..

 

Padded Inputs

Use the padding property to add space inside the text field.

Tip: When you have many inputs after each other, you might also want to add some margin, to add more space outside of them:

First Name  Last Name 

Example

input[type=text] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  box-sizing: border-box;
}

Note that we have set the box-sizing property to border-box. This makes sure that the padding and eventually borders are included in the total width and height of the elements.

Bordered Inputs

Use the border property to change the border size and color, and use the border-radius property to add rounded corners:

First Name 

Example

input[type=text] {
  border: 2px solid red;
  border-radius: 4px;
}

If you only want a bottom border, use the border-bottom property:

First Name 

Example

input[type=text] {
  border: none;
  border-bottom: 2px solid red;
}

Colored Inputs

Use the background-color property to add a background color to the input, and the color property to change the text color:

Example

input[type=text] {
  background-color: #3CBC8D;
  color: white;
}

Focused Inputs

By default, some browsers will add a blue outline around the input when it gets focus (clicked on). You can remove this behavior by adding outline: none; to the input.

Use the :focus selector to do something with the input field when it gets focus:

Example

input[type=text]:focus {
  background-color: lightblue;
}

Example

input[type=text]:focus {
  border: 3px solid #555;
}

Input with icon/image

If you want an icon inside the input, use the background-image property and position it with the background-position property. Also notice that we add a large left padding to reserve the space of the icon:

Example

input[type=text] {
  background-color: white;
  background-image: url('searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  padding-left: 40px;
}

Animated Search Input

In this example we use the CSS transition property to animate the width of the search input when it gets focus.

Example

input[type=text] {
  transition: width 0.4s ease-in-out;
}

input[type=text]:focus {
  width: 100%;
}

Styling Textareas

Tip: Use the resize property to prevent textareas from being resized (disable the "grabber" in the bottom right corner):

Example

textarea {
  width: 100%;
  height: 150px;
  padding: 12px 20px;
  box-sizing: border-box;
  border: 2px solid #ccc;
  border-radius: 4px;
  background-color: #f8f8f8;
  resize: none;
}

Styling Select Menus

Top of Form

             

Bottom of Form

Example

select {
  width: 100%;
  padding: 16px 20px;
  border: none;
  border-radius: 4px;
  background-color: #f1f1f1;
}

Styling Input Buttons

 

Example

input[type=button], input[type=submit], input[type=reset] {
  background-color: #04AA6D;
  border: none;
  color: white;
  padding: 16px 32px;
  text-decoration: none;
  margin: 4px 2px;
  cursor: pointer;
}

/* Tip: use width: 100% for full-width buttons */

Responsive Form

Resize the browser window to see the effect. When the screen is less than 600px wide, make the two columns stack on top of each other instead of next to each other.

CSS Counters

Pizza

Hamburger

Hotdogs

CSS counters are "variables" maintained by CSS whose values can be incremented by CSS rules (to track how many times they are used). Counters let you adjust the appearance of content based on its placement in the document.


Automatic Numbering With Counters

CSS counters are like "variables". The variable values can be incremented by CSS rules (which will track how many times they are used).

To work with CSS counters we will use the following properties:

  • counter-reset - Creates or resets a counter
  • counter-increment - Increments a counter value
  • content - Inserts generated content
  • counter() or counters() function - Adds the value of a counter to an element

To use a CSS counter, it must first be created with counter-reset.

The following example creates a counter for the page (in the body selector), then increments the counter value for each <h2> element and adds "Section <value of the counter>:" to the beginning of each <h2> element:

Example

body {
  counter-reset: section;
}

h2::before {
  counter-increment: section;
  content: "Section " counter(section) ": ";
}

Nesting Counters

The following example creates one counter for the page (section) and one counter for each <h1> element (subsection). The "section" counter will be counted for each <h1> element with "Section <value of the section counter>.", and the "subsection" counter will be counted for each <h2> element with "<value of the section counter>.<value of the subsection counter>":

Example

body {
  counter-reset: section;
}

h1 {
  counter-reset: subsection;
}

h1::before {
  counter-increment: section;
  content: "Section " counter(section) ". ";
}

h2::before {
  counter-increment: subsection;
  content: counter(section) "." counter(subsection) " ";
}

A counter can also be useful to make outlined lists because a new instance of a counter is automatically created in child elements. Here we use the counters() function to insert a string between different levels of nested counters:

Example

ol {
  counter-reset: section;
  list-style-type: none;
}

li::before {
  counter-increment: section;
  content: counters(section,".") " ";
}

 CSS Counter Properties

Property

Description

content

Used with the ::before and ::after pseudo-elements, to insert generated content

counter-increment

Increments one or more counter values

counter-reset

Creates or resets one or more counters

counter()

Returns the current value of the named counter

CSS Website Layout

Website Layout

A website is often divided into headers, menus, content and a footer:

Header

Navigation Menu

Content

Main Content

Content

Footer

There are tons of different layout designs to choose from. However, the structure above, is one of the most common, and we will take a closer look at it in this tutorial.

Header

A header is usually located at the top of the website (or right below a top navigation menu). It often contains a logo or the website name:

Example

.header {
  background-color: #F1F1F1;
  text-align: center;
  padding: 20px;
}

Result

Header

Navigation Bar

A navigation bar contains a list of links to help visitors navigating through your website:

Example

/* The navbar container */
.topnav {
  overflow: hidden;
  background-color: #333;
}

/* Navbar links */
.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

/* Links - change color on hover */
.topnav a:hover {
  background-color: #ddd;
  color: black;
}

Result

LinkLinkLink

Content

The layout in this section, often depends on the target users. The most common layout is one (or combining them) of the following:

  • 1-column (often used for mobile browsers)
  • 2-column (often used for tablets and laptops)
  • 3-column layout (only used for desktops)

1-column:

2-column:

3-column:

We will create a 3-column layout, and change it to a 1-column layout on smaller screens:

Example

/* Create three equal columns that float next to each other */
.column {
  float: left;
  width: 33.33%;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

/* Responsive layout - makes the three columns stack on top of each other instead of next to each other on smaller screens (600px wide or less) */
@media screen and (max-width: 600px) {
  .column {
    width: 100%;
  }
}

Result

Column

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique.

Column

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique.

Column

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique.

Unequal Columns

The main content is the biggest and the most important part of your site.

It is common with unequal column widths, so that most of the space is reserved for the main content. The side content (if any) is often used as an alternative navigation or to specify information relevant to the main content. Change the widths as you like, only remember that it should add up to 100% in total:

Example

.column {
  float: left;
}

/* Left and right column */
.column.side {
  width: 25%;
}

/* Middle column */
.column.middle {
  width: 50%;
}

/* Responsive layout - makes the three columns stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) {
  .column.side, .column.middle {
    width: 100%;
  }
}

Result

Side

Lorem ipsum dolor sit amet, consectetur adipiscing elit...

Main Content

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique. Quisque vehicula, risus eget aliquam placerat, purus leo tincidunt eros, eget luctus quam orci in velit. Praesent scelerisque tortor sed accumsan convallis.

Side

Lorem ipsum dolor sit amet, consectetur adipiscing elit...

Footer

The footer is placed at the bottom of your page. It often contains information like copyright and contact info:

Example

.footer {
  background-color: #F1F1F1;
  text-align: center;
  padding: 10px;
}

Result

Footer

Responsive Website Layout

By using some of the CSS code above, we have created a responsive website layout, which varies between two columns and full-width columns depending on screen width:

CSS Units

CSS has several different units for expressing a length.

Many CSS properties take "length" values, such as widthmarginpaddingfont-size, etc.

Length is a number followed by a length unit, such as 10px2em, etc.

Example

Set different length values, using px (pixels):

h1 {
  font-size: 60px;
}

{
  font-size: 25px;
  line-height: 50px;
}

Note: A whitespace cannot appear between the number and the unit. However, if the value is 0, the unit can be omitted.

For some CSS properties, negative lengths are allowed.

There are two types of length units: absolute and relative.

Absolute Lengths

The absolute length units are fixed and a length expressed in any of these will appear as exactly that size.

Absolute length units are not recommended for use on screen, because screen sizes vary so much. However, they can be used if the output medium is known, such as for print layout.

Unit

Description

cm

centimeters

mm

millimeters

in

inches (1in = 96px = 2.54cm)

px *

pixels (1px = 1/96th of 1in)

pt

points (1pt = 1/72 of 1in)

pc

picas (1pc = 12 pt)

* Pixels (px) are relative to the viewing device. For low-dpi devices, 1px is one device pixel (dot) of the display. For printers and high resolution screens 1px implies multiple device pixels.

Relative Lengths

Relative length units specify a length relative to another length property. Relative length units scale better between different rendering mediums.

Unit

Description

em

Relative to the font-size of the element (2em means 2 times the size of the current font)

Try it

ex

Relative to the x-height of the current font (rarely used)

Try it

ch

Relative to width of the "0" (zero)

Try it

rem

Relative to font-size of the root element

Try it

vw

Relative to 1% of the width of the viewport*

Try it

vh

Relative to 1% of the height of the viewport*

Try it

vmin

Relative to 1% of viewport's* smaller dimension

Try it

vmax

Relative to 1% of viewport's* larger dimension

Try it

%

Relative to the parent element

Try it

Tip: The em and rem units are practical in creating perfectly scalable layout!
* Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm.

CSS The !important Rule

What is !important?

The !important rule in CSS is used to add more importance to a property/value than normal.

In fact, if you use the !important rule, it will override ALL previous styling rules for that specific property on that element!

Let us look at an example:

Example

#myid {
  background-color: blue;
}

.myclass {
  background-color: gray;
}

{
  background-color: red !important;
}

Example Explained

In the example above. all three paragraphs will get a red background color, even though the ID selector and the class selector have a higher specificity. The !important rule overrides the background-color property in both cases.


Important About !important

The only way to override an !important rule is to include another !important rule on a declaration with the same (or higher) specificity in the source code - and here the problem starts! This makes the CSS code confusing and the debugging will be hard, especially if you have a large style sheet!

Here we have created a simple example. It is not very clear, when you look at the CSS source code, which color is considered most important:

Example

#myid {
  background-color: blue !important;
}

.myclass {
  background-color: gray !important;
}

{
  background-color: red !important;
}

Tip: It is good to know about the !important rule. You might see it in some CSS source code. However, do not use it unless you absolutely have to.

Maybe One or Two Fair Uses of !important

One way to use !important is if you have to override a style that cannot be overridden in any other way. This could be if you are working on a Content Management System (CMS) and cannot edit the CSS code. Then you can set some custom styles to override some of the CMS styles.

Another way to use !important is: Assume you want a special look for all buttons on a page. Here, buttons are styled with a gray background color, white text, and some padding and border:

Example

.button {
  background-color: #8c8c8c;
  color: white;
  padding: 5px;
  border: 1px solid black;
}

The look of a button can sometimes change if we put it inside another element with higher specificity, and the properties get in conflict. Here is an example of this:

Example

.button {
  background-color: #8c8c8c;
  color: white;
  padding: 5px;
  border: 1px solid black;
}

#myDiv a {
  color: red;
  background-color: yellow;
}

To "force" all buttons to have the same look, no matter what, we can add the !important rule to the properties of the button, like this:

Example

.button {
  background-color: #8c8c8c !important;
  color: white !important;
  padding: 5px !important;
  border: 1px solid black !important;
}

#myDiv a {
  color: red;
  background-color: yellow;
}

CSS Math Functions

❮ PreviousNext ❯


The CSS math functions allow mathematical expressions to be used as property values. Here, we will explain the calc()max() and min() functions.


The calc() Function

The calc() function performs a calculation to be used as the property value.

CSS Syntax

calc(expression)

Value

Description

expression

Required. A mathematical expression. The result will be used as the value.
The following operators can be used: + - * /

Let us look at an example:

Example

Use calc() to calculate the width of a <div> element:

#div1 {
  position: absolute;
  left: 50px;
  width: calc(100% - 100px);
  border: 1px solid black;
  background-color: yellow;
  padding: 5px;
}

The max() Function

The max() function uses the largest value, from a comma-separated list of values, as the property value.

CSS Syntax

max(value1value2, ...)

Value

Description

value1value2, ...

Required. A list of comma-separated values - where the largest value is chosen

Let us look at an example:

Example

Use max() to set the width of #div1 to whichever value is largest, 50% or 300px:

#div1 {
  background-color: yellow;
  height: 100px;
  width: max(50%, 300px);
}

The min() Function

The min() function uses the smallest value, from a comma-separated list of values, as the property value.

CSS Syntax

min(value1value2, ...)

Value

Description

value1value2, ...

Required. A list of comma-separated values - where the smallest value is chosen

Let us look at an example:

Example

Use min() to set the width of #div1 to whichever value is smallest, 50% or 300px:

#div1 {
  background-color: yellow;
  height: 100px;
  width: min(50%, 300px);
}

All CSS Math Functions

Function

Description

calc()

Allows you to perform calculations to determine CSS property values

max()

Uses the largest value, from a comma-separated list of values, as the property value

min()

Uses the smallest value, from a comma-separated list of values, as the property value

 


Tags

Post a Comment

0Comments
Post a Comment (0)