HTML Introduction


HTML is the standard markup language for creating Web pages.


What is HTML?

  • HTML stands for Hyper Text Markup Language
  • HTML is the standard markup language for creating Web pages
  • HTML describes the structure of a Web page
  • HTML consists of a series of elements
  • HTML elements tell the browser how to display the content
  • HTML elements label pieces of content such as "this is a heading", "this is a paragraph", "this is a link", etc.

A Simple HTML Document

Example

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>

Example Explained

  • The <!DOCTYPE html> declaration defines that this document is an HTML5 document
  • The <html> element is the root element of an HTML page
  • The <head> element contains meta information about the HTML page
  • The <title> element specifies a title for the HTML page (which is shown in the browser's title bar or in the page's tab)
  • The <body> element defines the document's body, and is a container for all the visible contents, such as headings, paragraphs, images, hyperlinks, tables, lists, etc.
  • The <h1> element defines a large heading
  • The <p> element defines a paragraph

What is an HTML Element?

An HTML element is defined by a start tag, some content, and an end tag:

<tagname> Content goes here... </tagname>

The HTML element is everything from the start tag to the end tag:

<h1>My First Heading</h1>
<p>My first paragraph.</p>
Start tag Element content End tag
<h1> My First Heading </h1>
<p> My first paragraph. </p>
<br> none none

Note: Some HTML elements have no content (like the <br> element). These elements are called empty elements. Empty elements do not have an end tag!



Web Browsers

The purpose of a web browser (Chrome, Edge, Firefox, Safari) is to read HTML documents and display them correctly.

A browser does not display the HTML tags, but uses them to determine how to display the document:

View in Browser


HTML Page Structure

Below is a visualization of an HTML page structure:

<html>
<head>
<title>Page title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>

Note: The content inside the <body> section will be displayed in a browser. The content inside the <title> element will be shown in the browser's title bar or in the page's tab.


HTML History

Since the early days of the World Wide Web, there have been many versions of HTML:

Year Version
1989 Tim Berners-Lee invented www
1991 Tim Berners-Lee invented HTML
1993 Dave Raggett drafted HTML+
1995 HTML Working Group defined HTML 2.0
1997 W3C Recommendation: HTML 3.2
1999 W3C Recommendation: HTML 4.01
2000 W3C Recommendation: XHTML 1.0
2008 WHATWG HTML5 First Public Draft
2012
2014
2016 W3C Candidate Recommendation: HTML 5.1
2017
2017

This tutorial follows the latest HTML5 standard.


CSS Tutorial

 

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

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

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


CSS Examples

Learn from over 300 examples! With our editor, you can edit the CSS, and click on a button to view the result.

 


Use the Menu

We recommend reading this tutorial, in the sequence listed in the menu.

If you have a large screen, the menu will always be present on the left.

If you have a small screen, open the menu by clicking the top menu sign .


CSS Templates

We have created some responsive W3.CSS templates for you to use.

You are free to modify, save, share, and use them in all your projects.

 



CSS HOME

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

p {
  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:

 

This is a paragraph.

 

When tags like , 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.

To solve this problem, the World Wide Web Consortium (W3C) created CSS.

CSS removed the style formatting from the HTML page!

If you don't know what HTML is, we suggest that you read our .


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 Introduction

CSS Syntax

 

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


CSS Syntax

 

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

elements will be center-aligned, with a red text color:

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

Example Explained

  • p is a selector in CSS (it points to the HTML element you want to style:

    ).

  • 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 Syntax

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)
  • (select elements based on a specific relationship between them)
  • (select elements based on a certain state)
  • (select and style a part of an element)
  • (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

elements on the page will be center-aligned, with a red text color: 

p {
  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

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

element will be styled according to class="center" and to class="large": 

This paragraph refers to two classes.

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

p {
  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;
}

Test Yourself With Exercises

Exercise:

Set the text color of all

elements to red.

 

 


All CSS Simple Selectors

Selector Example Example description
  #firstname Selects the element with id="firstname"
  .intro Selects all elements with class="intro"
  p.intro Selects only

elements with class="intro"

  * Selects all elements
  p Selects all

elements

  div, p Selects all
elements and all

elements

 

 
CSS Selectors
 

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 element, inside the head section.

Example

External styles are defined within the element, inside the section of an HTML page:

This is a paragraph.

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 (20) and the unit (px):
Incorrect (space): margin-left: 20 px;
Correct (no space): 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

This is a paragraph.

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:

This is a paragraph.

 

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

element:

 

h1 {
  color: navy;
}

Then, assume that an internal style sheet also has the following style for the

element:

 

h1 {
  color: orange;   
}

Example

If the internal style is defined after the link to the external style sheet, the

elements will be "orange":

 




Example

However, if the internal style is defined before the link to the external style sheet, the

elements will be "navy": 

 





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.

 

Ever heard about W3Schools Spaces? Here you can create your own website, or save code snippets for later use, for free.

* no credit card required


Test Yourself With Exercises

Exercise:

Add an external style sheet with the URL: "mystyle.css".





  
 

 

 

 
CSS How To

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


Hello World!







CSS Comments

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
LightGray

CSS/HTML support .


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

Hello World


Lorem ipsum...



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

Hello World


Lorem ipsum...


Ut wisi enim...



CSS Border Color

You can set the color of borders:

Hello World

Hello World

Hello World

Example

Hello World


Hello World


Hello World


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%)

Same as color name "Tomato", but 50% transparent:

rgba(255, 99, 71, 0.5)
hsla(9, 100%, 64%, 0.5)

Example

...


...


...



...


...

Learn more about Color Values

You will learn more about , and in the next chapters.


CSS Colors

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
LightGray

CSS/HTML support .


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

Hello World


Lorem ipsum...



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

Hello World


Lorem ipsum...


Ut wisi enim...



CSS Border Color

You can set the color of borders:

Hello World

Hello World

Hello World

Example

Hello World


Hello World


Hello World


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%)

Same as color name "Tomato", but 50% transparent:

rgba(255, 99, 71, 0.5)
hsla(9, 100%, 64%, 0.5)

Example

...


...


...



...


...

Learn more about Color Values

You will learn more about , and in the next chapters.


Colors

CSS RGB Colors


An RGB color value represents RED, GREEN, and BLUE light sources.


RGB Value

In CSS, a color can be specified as an RGB value, using this formula:

rgb(red, green, blue)

Each parameter (red, green, and blue) defines the intensity of the color between 0 and 255.

For example, rgb(255, 0, 0) is displayed as red, because red is set to its highest value (255) and the others are set to 0.

To display black, set all color parameters to 0, like this: rgb(0, 0, 0).

To display white, set all color parameters to 255, like this: rgb(255, 255, 255).

Experiment by mixing the RGB values below:

 

RED

255

GREEN

0

BLUE

0

Example

rgb(255, 0, 0)
rgb(0, 0, 255)
rgb(60, 179, 113)
rgb(238, 130, 238)
rgb(255, 165, 0)
rgb(106, 90, 205)

Shades of gray are often defined using equal values for all the 3 light sources:

Example

rgb(60, 60, 60)
rgb(90, 90, 90)
rgb(120, 120, 120)
rgb(180, 180, 180)
rgb(210, 210, 210)
rgb(240, 240, 240)



RGBA Value

RGBA color values are an extension of RGB color values with an alpha channel - which specifies the opacity for a color.

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 (not transparent at all):

Experiment by mixing the RGBA values below:

 

RED

255

GREEN

0

BLUE

0

ALPHA

0

Example

rgba(255, 99, 71, 0)
rgba(255, 99, 71, 0.2)
rgba(255, 99, 71, 0.4)
rgba(255, 99, 71, 0.6)
rgba(255, 99, 71, 0.8)
rgba(255, 99, 71, 1)


RGB

CSS HEX Colors

 

A hexadecimal color is specified with: #RRGGBB, where the RR (red), GG (green) and BB (blue) hexadecimal integers specify the components of the color.


HEX Value

In CSS, a color can be specified using a hexadecimal value in the form:

#rrggbb

Where rr (red), gg (green) and bb (blue) are hexadecimal values between 00 and ff (same as decimal 0-255).

For example, #ff0000 is displayed as red, because red is set to its highest value (ff) and the others are set to the lowest value (00).

To display black, set all values to 00, like this: #000000.

To display white, set all values to ff, like this: #ffffff.  

Experiment by mixing the HEX values below:

 

 

RED

ff

GREEN

0

BLUE

0

Example

#ff0000
#0000ff
#3cb371
#ee82ee
#ffa500
#6a5acd

Shades of gray are often defined using equal values for all the 3 light sources:

Example

#3c3c3c
#616161
#787878
#b4b4b4
#f0f0f0
#f9f9f9


3 Digit HEX Value

Sometimes you will see a 3-digit hex code in the CSS source.

The 3-digit hex code is a shorthand for some 6-digit hex codes.

The 3-digit hex code has the following form:

#rgb

Where r, g, and b represent the red, green, and blue components with values between 0 and f.

The 3-digit hex code can only be used when both the values (RR, GG, and BB) are the same for each component. So, if we have #ff00cc, it can be written like this: #f0c.

Here is an example:

Example

body {
  background-color: #fc9; /* same as #ffcc99 */
}

h1 {
  color: #f0f; /* same as #ff00ff */
}

p {
  color: #b58; /* same as #bb5588 */
}

 

 
HEX

CSS HSL Colors


HSL stands for hue, saturation, and lightness.


HSL Value

In CSS, a color can be specified using hue, saturation, and lightness (HSL) in the form:

hsl(hue, saturation, lightness)

Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, and 240 is blue.

Saturation is a percentage value. 0% means a shade of gray, and 100% is the full color.

Lightness is also a percentage. 0% is black, 50% is neither light or dark, 100% is white

Experiment by mixing the HSL values below:

 

HUE

0

SATURATION

100%

LIGHTNESS

50%

Example

hsl(0, 100%, 50%)
hsl(240, 100%, 50%)
hsl(147, 50%, 47%)
hsl(300, 76%, 72%)
hsl(39, 100%, 50%)
hsl(248, 53%, 58%)


Saturation

Saturation can be described as the intensity of a color.

100% is pure color, no shades of gray.

50% is 50% gray, but you can still see the color.

0% is completely gray; you can no longer see the color.

Example

hsl(0, 100%, 50%)
hsl(0, 80%, 50%)
hsl(0, 60%, 50%)
hsl(0, 40%, 50%)
hsl(0, 20%, 50%)
hsl(0, 0%, 50%)



Lightness

The lightness of a color can be described as how much light you want to give the color, where 0% means no light (black), 50% means 50% light (neither dark nor light) and 100% means full lightness (white).

Example

hsl(0, 100%, 0%)
hsl(0, 100%, 25%)
hsl(0, 100%, 50%)
hsl(0, 100%, 75%)
hsl(0, 100%, 90%)
hsl(0, 100%, 100%)


Shades of Gray

Shades of gray are often defined by setting the hue and saturation to 0, and adjust the lightness from 0% to 100% to get darker/lighter shades:

Example

hsl(0, 0%, 0%)
hsl(0, 0%, 24%)
hsl(0, 0%, 47%)
hsl(0, 0%, 71%)
hsl(0, 0%, 94%)
hsl(0, 0%, 100%)


HSLA Value

HSLA color values are an extension of HSL color values with an alpha channel - which specifies the opacity for a color.

An HSLA color value is specified with:

hsla(hue, saturation, lightness, alpha)

The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at all):

Experiment by mixing the HSLA values below:

 

HUE

0

SATURATION

100%

LIGHTNESS

50%

ALPHA

0.5

Example

hsla(9, 100%, 64%, 0)
hsla(9, 100%, 64%, 0.2)
hsla(9, 100%, 64%, 0.4)
hsla(9, 100%, 64%, 0.6)
hsla(9, 100%, 64%, 0.8)
hsla(9, 100%, 64%, 1)


HSL

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)"

Look at for a complete list of possible color values.


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

p {
  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

You learned from our , that you can use RGB as a color value. In addition to RGB, you can use an RGB color value with an alpha channel (RGBA) - which specifies the opacity for a color.

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).

Tip: You will learn more about RGBA Colors in our .

Example

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

The CSS Background Color Property

Property Description
Sets the background color of an element

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)"

Look at for a complete list of possible color values.


Other Elements

You can set the background color for any HTML elements:

Example

Here, the

,

, and

elements will have different background colors: 

h1 {
  background-color: green;
}

div {
  background-color: lightblue;
}

p {
  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

You learned from our , that you can use RGB as a color value. In addition to RGB, you can use an RGB color value with an alpha channel (RGBA) - which specifies the opacity for a color.

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).

Tip: You will learn more about RGBA Colors in our .

Example

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

The CSS Background Color Property

Property Description
Sets the background color of an element

Background Color

CSS Background Image


CSS background-image

The background-image property specifies an image to use as the background of an element.

By default, the image is repeated so it covers the entire element.

Example

Set the background image for a page: 

body {
  background-image: url("paper.gif");
}

Example

This example shows a bad combination of text and background image. The text is hardly readable: 

body {
  background-image: url("bgdesert.jpg");
}

Note: When using a background image, use an image that does not disturb the text.

The background image can also be set for specific elements, like the

element:

Example

p {
  background-image: url("paper.gif");
}

The CSS Background Image Property

Property Description
Sets the background image for an element

Background Image

CSS Background Image Repeat


CSS background-repeat

By default, the background-image property repeats an image both horizontally and vertically.

Some images should be repeated only horizontally or vertically, or they will look strange, like this:

Example

body {
  background-image: url("gradient_bg.png");
}

If the image above is repeated only horizontally (background-repeat: repeat-x;), the background will look better:

Example

body {
  background-image: url("gradient_bg.png");
  background-repeat: repeat-x;
}

Tip: To repeat an image vertically, set background-repeat: repeat-y;


CSS background-repeat: no-repeat

Showing the background image only once is also specified by the background-repeat property:

Example

Show the background image only once:

body {
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
}

In the example above, the background image is placed in the same place as the text. We want to change the position of the image, so that it does not disturb the text too much.


CSS background-position

The background-position property is used to specify the position of the background image.

Example

Position the background image in the top-right corner: 

body {
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
  background-position: right top;
}

The CSS Background Repeat and Position Properties

Property Description
Sets the starting position of a background image
Sets how a background image will be repeated

Background Repeat

CSS Background Attachment


CSS background-attachment

The background-attachment property specifies whether the background image should scroll or be fixed (will not scroll with the rest of the page):

Example

Specify that the background image should be fixed:

body {
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
  background-position: right top;
  background-attachment: fixed;
}

Example

Specify that the background image should scroll with the rest of the page:

body {
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
  background-position: right top;
  background-attachment: scroll;
}

The CSS Background Attachment Property

Property Description
Sets whether a background image is fixed or scrolls with the rest of the page

Background Attachment

CSS Background Shorthand

 

CSS background - Shorthand property

To shorten the code, it is also possible to specify all the background properties in one single property. This is called a shorthand property.

Instead of writing:

body {
  background-color: #ffffff;
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
  background-position: right top;
}

You can use the shorthand property background:

Example

Use the shorthand property to set the background properties in one declaration:

body {
  background: #ffffff url("img_tree.png") no-repeat right top;
}

When using the shorthand property the order of the property values is:

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

It does not matter if one of the property values is missing, as long as the other ones are in this order. Note that we do not use the background-attachment property in the examples above, as it does not have a value.


Test Yourself With Exercises

Exercise:

Set the background color of the

element to "lightblue".

 

 


All CSS Background Properties

Property Description
  Sets all the background properties in one declaration
  Sets whether a background image is fixed or scrolls with the rest of the page
  Specifies the painting area of the background
  Sets the background color of an element
  Sets the background image for an element
  Specifies where the background image(s) is/are positioned
  Sets the starting position of a background image
  Sets how a background image will be repeated
  Specifies the size of the background image(s)

 

 
Background Shorthand

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 Borders

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!


Borders

CSS Border Width


CSS Border Width

The border-width property specifies the width of the four borders.

The width can be set as a specific size (in px, pt, cm, em, etc) or by using one of the three pre-defined values: thin, medium, or thick:

Example

Demonstration of the different border widths:

p.one {
  border-style: solid;
  border-width: 5px;
}

p.two {
  border-style: solid;
  border-width: medium;
}

p.three {
  border-style: dotted;
  border-width: 2px;
}

p.four {
  border-style: dotted;
  border-width: thick;
}

Result:

5px border-width
medium border-width
2px border-width
thick border-width

Specific Side Widths

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

Example

p.one {
  border-style: solid;
  border-width: 5px 20px; /* 5px top and bottom, 20px on the sides */
}

p.two {
  border-style: solid;
  border-width: 20px 5px; /* 20px top and bottom, 5px on the sides */
}

p.three {
  border-style: solid;
  border-width: 25px 10px 4px 35px; /* 25px top, 10px right, 4px bottom and 35px left */
}

Border Width

CSS Border Color


CSS Border Color

The border-color property is used to set the color of the four borders.

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%)"
  • transparent

Note: If border-color is not set, it inherits the color of the element.

Example

Demonstration of the different border colors:

p.one {
  border-style: solid;
  border-color: red;
}

p.two {
  border-style: solid;
  border-color: green;
}

p.three {
  border-style: dotted;
  border-color: blue;
}

Result:

Red border
Green border
Blue border

Specific Side Colors

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

Example

p.one {
  border-style: solid;
  border-color: red green blue yellow; /* red top, green right, blue bottom and yellow left */
}


HEX Values

The color of the border can also be specified using a hexadecimal value (HEX):

Example

p.one {
  border-style: solid;
  border-color: #ff0000; /* red */
}

RGB Values

Or by using RGB values:

Example

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

HSL Values

You can also use HSL values:

Example

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

You can learn more about HEX, RGB and HSL values in our chapters.


Border Color

CSS Border Sides


CSS Border - Individual Sides

From the examples on the previous pages, you have seen that it is possible to specify a different border for each side.

In CSS, there are also properties for specifying each of the borders (top, right, bottom, and left):

Example

p {
  border-top-style: dotted;
  border-right-style: solid;
  border-bottom-style: dotted;
  border-left-style: solid;
}

Result:

Different Border Styles

The example above gives the same result as this:

Example

p {
  border-style: dotted solid;
}

So, here is how it works:

If the border-style property has four values:

  • border-style: dotted solid double dashed;
    • top border is dotted
    • right border is solid
    • bottom border is double
    • left border is dashed

If the border-style property has three values:

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

If the border-style property has two values:

  • border-style: dotted solid;
    • top and bottom borders are dotted
    • right and left borders are solid

If the border-style property has one value:

  • border-style: dotted;
    • all four borders are dotted

Example

/* Four values */
p {
  border-style: dotted solid double dashed;
}

/* Three values */
p {
  border-style: dotted solid double;
}

/* Two values */
p {
  border-style: dotted solid;
}

/* One value */
p {
  border-style: dotted;
}

The border-style property is used in the example above. However, it also works with border-width and border-color.


Border Sides

CSS Shorthand Border Property


CSS Border - Shorthand Property

Like you saw in the previous page, there are many properties to consider when dealing with borders.

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

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

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

Example

p {
  border: 5px solid red;
}

Result:

Some text

You can also specify all the individual border properties for just one side:

Left Border

p {
  border-left: 6px solid red;
}

Result:

Some text

Bottom Border

p {
  border-bottom: 6px solid red;
}

Result:

Some text


Border Shorthand

CSS Rounded Borders

 

CSS Rounded Borders

The border-radius property is used to add rounded borders to an element:

Normal border

Round border

Rounder border

Roundest border

Example

p {
  border: 2px solid red;
  border-radius: 5px;
}

More Examples


This example demonstrates a shorthand property for setting all of the properties for the top border in one declaration.


This example demonstrates how to set the style of the bottom border.


This example demonstrates how to set the width of the left border.


This example demonstrates how to set the color of the four borders. It can have from one to four colors.


This example demonstrates how to set the color of the right border.



Test Yourself With Exercises

Exercise:

Use the border shorthand property to set a "4px", "dotted", "red" border for the

elements.





 


All CSS Border Properties

Property Description
  Sets all the border properties in one declaration
  Sets all the bottom border properties in one declaration
  Sets the color of the bottom border
  Sets the style of the bottom border
  Sets the width of the bottom border
  Sets the color of the four borders
  Sets all the left border properties in one declaration
  Sets the color of the left border
  Sets the style of the left border
  Sets the width of the left border
  Sets all the four border-*-radius properties for rounded corners
  Sets all the right border properties in one declaration
  Sets the color of the right border
  Sets the style of the right border
  Sets the width of the right border
  Sets the style of the four borders
  Sets all the top border properties in one declaration
  Sets the color of the top border
  Sets the style of the top border
  Sets the width of the top border
  Sets the width of the four borders

 

 
Rounded Borders

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

element:

p {
  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:

p {
  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: 

p {
  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: 

p {
  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: 

p {
  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

element be inherited from the parent element (

):

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
A shorthand property for setting all the margin properties in one declaration
Sets the bottom margin of an element
Sets the left margin of an element
Sets the right margin of an element
Sets the top margin of an element

CSS Margins

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

element:

p {
  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:

p {
  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: 

p {
  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: 

p {
  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: 

p {
  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

element be inherited from the parent element (

):

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
A shorthand property for setting all the margin properties in one declaration
Sets the bottom margin of an element
Sets the left margin of an element
Sets the right margin of an element
Sets the top margin of an element

Margins

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

element has a bottom margin of 50px and the

element has a top margin set to 20px.

Common sense would seem to suggest that the vertical margin between the

and the

would be a total of 70px (50px + 20px). But due to margin collapse, the actual margin ends up being 50px.


Test Yourself With Exercises

Exercise:

Add a 20 pixels left margin to the



All CSS Margin Properties

Property Description
A shorthand property for setting all the margin properties in one declaration
Sets the bottom margin of an element
Sets the left margin of an element
Sets the right margin of an element
Sets the top margin of an element

Margin Collapse

CSS Padding

 

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

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

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

element is given a width of 300px. However, the actual width of the
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;
}

More Examples


This example demonstrates how to set the left padding of a

element.


This example demonstrates how to set the right padding of a

element.


This example demonstrates how to set the top padding of a

element.


This example demonstrates how to set the bottom padding of a

element.


Test Yourself With Exercises

Exercise:

Set the top padding of the

 


All CSS Padding Properties

Property Description
  A shorthand property for setting all the padding properties in one declaration
  Sets the bottom padding of an element
  Sets the left padding of an element
  Sets the right padding of an element
  Sets the top padding of an element

 
CSS Padding

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

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

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

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

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

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


Try it Yourself - Examples


This example demonstrates how to set the height and width of different elements.


This example demonstrates how to set the height and width of an image using a percent value.


This example demonstrates how to set a minimum width and a maximum width of an element using a pixel value.


This example demonstrates how to set a minimum height and a maximum height of an element using a pixel value.


Test Yourself With Exercises

Exercise:

Set the height of the

All CSS Dimension Properties

Property Description
Sets the height of an element
Sets the maximum height of an element
Sets the maximum width of an element
Sets the minimum height of an element
Sets the minimum width of an element
Sets the width of an element

CSS Height/Width

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

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


Test Yourself With Exercises

Exercise:

Set the width of the

element to "200px".
 
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
 

 
CSS Box Model

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

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

 

 
Outline

CSS Outline Width

 

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

 

 
Outline Width

CSS Outline Color


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 */
}

You can learn more about HEX, RGB and HSL values in our chapters.


Outline Color

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

Outline Shorthand

CSS Outline Offset


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

p {
  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

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


Test Yourself With Exercises

Exercise:

Set a solid, 5px outline border for the

element.





Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.


All CSS Outline Properties

Property Description
A shorthand property for setting outline-width, outline-style, and outline-color in one declaration
Sets the color of an outline
Specifies the space between an outline and the edge or border of an element
Sets the style of an outline
Sets the width of an outline

Outline Offset

CSS Text

 

CSS has a lot of properties for formatting text.

 


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)"

Look at for a complete list of possible color values.

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
  Specifies the color of text

 

 
CSS Text

CSS Text

 

CSS has a lot of properties for formatting text.

 


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)"

Look at for a complete list of possible color values.

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
  Specifies the color of text

 

 
Text Color

CSS Text Alignment


Text Alignment and Text Direction

In this chapter you will learn about the following properties:

  • text-align
  • text-align-last
  • direction
  • unicode-bidi
  • vertical-align

Text Alignment

The text-align property is used to set the horizontal alignment of a text.

A text can be left or right aligned, centered, or justified.

The following example shows center aligned, and left and right aligned text (left alignment is default if text direction is left-to-right, and right alignment is default if text direction is right-to-left):

Example

h1 {
  text-align: center;
}

h2 {
  text-align: left;
}

h3 {
  text-align: right;
}

When the text-align property is set to "justify", each line is stretched so that every line has equal width, and the left and right margins are straight (like in magazines and newspapers):

Example

div {
  text-align: justify;
}

Text Align Last

The text-align-last property specifies how to align the last line of a text.

Example

Align the last line of text in three

elements:

p.a {
  text-align-last: right;
}

p.b {
  text-align-last: center;
}

p.c {
  text-align-last: justify;
}


Text Direction

The direction and unicode-bidi properties can be used to change the text direction of an element:

Example

p {
  direction: rtl;
  unicode-bidi: bidi-override;
}

Vertical Alignment

The vertical-align property sets the vertical alignment of an element.

Example

Set the vertical alignment of an image in a text: 

img.a {
  vertical-align: baseline;
}

img.b {
  vertical-align: text-top;
}

img.c {
  vertical-align: text-bottom;
}

img.d {
  vertical-align: sub;
}

img.e {
  vertical-align: super;
}

The CSS Text Alignment/Direction Properties

Property Description
Specifies the text direction/writing direction
Specifies the horizontal alignment of text
Specifies how to align the last line of a text
Used together with the property to set or return whether the text should be overridden to support multiple languages in the same document
Sets the vertical alignment of an element

Text Alignment

CSS Text Decoration


Text Decoration

In this chapter you will learn about the following properties:

  • text-decoration-line
  • text-decoration-color
  • text-decoration-style
  • text-decoration-thickness
  • text-decoration

Add a Decoration Line to Text

The text-decoration-line property is used to add a decoration line to text.

Tip: You can combine more than one value, like overline and underline to display lines both over and under a text.

Example

h1 {
  text-decoration-line: overline;
}

h2 {
  text-decoration-line: line-through;
}

h3 {
  text-decoration-line: underline;
}

p {
  text-decoration-line: overline underline;
}

Note: It is not recommended to underline text that is not a link, as this often confuses the reader.


Specify a Color for the Decoration Line

The text-decoration-color property is used to set the color of the decoration line.

Example

h1 {
  text-decoration-line: overline;
  text-decoration-color: red;
}

h2 {
  text-decoration-line: line-through;
  text-decoration-color: blue;
}

h3 {
  text-decoration-line: underline;
  text-decoration-color: green;
}

p {
  text-decoration-line: overline underline;
  text-decoration-color: purple;
}


Specify a Style for the Decoration Line

The text-decoration-style property is used to set the style of the decoration line.

Example

h1 {
  text-decoration-line: underline;
  text-decoration-style: solid;
}

h2 {
  text-decoration-line: underline;
  text-decoration-style: double;
}

h3 {
  text-decoration-line: underline;
  text-decoration-style: dotted;
}

p.ex1 {
  text-decoration-line: underline;
  text-decoration-style: dashed;
}

p.ex2 {
  text-decoration-line: underline;
  text-decoration-style: wavy;
}

p.ex3 {
  text-decoration-line: underline;
  text-decoration-color: red;
  text-decoration-style: wavy;
}

Specify the Thickness for the Decoration Line

The text-decoration-thickness property is used to set the thickness of the decoration line.

Example

h1 {
  text-decoration-line: underline;
  text-decoration-thickness: auto;
}

h2 {
  text-decoration-line: underline;
  text-decoration-thickness: 5px;
}

h3 {
  text-decoration-line: underline;
  text-decoration-thickness: 25%;
}

p {
  text-decoration-line: underline;
  text-decoration-color: red;
  text-decoration-style: double;
  text-decoration-thickness: 5px;
}

The Shorthand Property

The text-decoration property is a shorthand property for:

  • text-decoration-line (required)
  • text-decoration-color (optional)
  • text-decoration-style (optional)
  • text-decoration-thickness (optional)

Example

h1 {
  text-decoration: underline;
}

h2 {
  text-decoration: underline red;
}

h3 {
  text-decoration: underline red double;
}

p {
  text-decoration: underline red double 5px;
}

A Small Tip

All links in HTML are underlined by default. Sometimes you see that links are styled with no underline. The text-decoration: none; is used to remove the underline from links, like this:

Example

a {
  text-decoration: none;
}

All CSS text-decoration Properties

Property Description
Sets all the text-decoration properties in one declaration
Specifies the color of the text-decoration
Specifies the kind of text decoration to be used (underline, overline, etc.)
Specifies the style of the text decoration (solid, dotted, etc.)
Specifies the thickness of the text decoration line

Text Decoration

CSS Text Transformation


Text Transformation

The text-transform property is used to specify uppercase and lowercase letters in a text.

It can be used to turn everything into uppercase or lowercase letters, or capitalize the first letter of each word:

Example

p.uppercase {
  text-transform: uppercase;
}

p.lowercase {
  text-transform: lowercase;
}

p.capitalize {
  text-transform: capitalize;
}

The CSS Text Transformation Property

Property Description
Controls the capitalization of text

Text Transformation

CSS Text Spacing


Text Spacing

In this chapter you will learn about the following properties:

  • text-indent
  • letter-spacing
  • line-height
  • word-spacing
  • white-space

Text Indentation

The text-indent property is used to specify the indentation of the first line of a text:

Example

p {
  text-indent: 50px;
}

Letter Spacing

The letter-spacing property is used to specify the space between the characters in a text.

The following example demonstrates how to increase or decrease the space between characters:

Example

h1 {
  letter-spacing: 5px;
}

h2 {
  letter-spacing: -2px;
}

Line Height

The line-height property is used to specify the space between lines:

Example

p.small {
  line-height: 0.8;
}

p.big {
  line-height: 1.8;
}


Word Spacing

The word-spacing property is used to specify the space between the words in a text.

The following example demonstrates how to increase or decrease the space between words:

Example

p.one {
  word-spacing: 10px;
}

p.two {
  word-spacing: -2px;
}

White Space

The white-space property specifies how white-space inside an element is handled.

This example demonstrates how to disable text wrapping inside an element:

Example

p {
  white-space: nowrap;
}

The CSS Text Spacing Properties

Property Description
Specifies the space between characters in a text
Specifies the line height
Specifies the indentation of the first line in a text-block
Specifies how to handle white-space inside an element
Specifies the space between words in a text

Text Spacing

CSS Text Shadow

 

Text Shadow

The text-shadow property adds shadow to text.

In its simplest use, you only specify the horizontal shadow (2px) and the vertical shadow (2px):

Text shadow effect!

Example

h1 {
  text-shadow: 2px 2px;
}

Next, add a color (red) to the shadow:

Text shadow effect!

Example

h1 {
  text-shadow: 2px 2px red;
}

Then, add a blur effect (5px) to the shadow:

Text shadow effect!

Example

h1 {
  text-shadow: 2px 2px 5px red;
}

More Text Shadow Examples

Example 1

Text-shadow on a white text:

h1 {
  color: white;
  text-shadow: 2px 2px 4px #000000;
}

Example 2

Text-shadow with red neon glow:

h1 {
  text-shadow: 0 0 3px #ff0000;
}

Example 3

Text-shadow with red and blue neon glow:

h1 {
  text-shadow: 0 0 3px #ff0000, 0 0 5px #0000ff;
}

Example 4

h1 {
  color: white;
  text-shadow: 1px 1px 2px black, 0 0 25px blue, 0 0 5px darkblue;
}

Tip: chapter to learn about how to change fonts, text size and the style of a text.

Tip: chapter to learn about different text effects.



Test Yourself With Exercises

Exercise:

Change the text color of all

elements to "red".


 


The CSS Text Shadow Property

Property Description
  Specifies the shadow effect added to text

 

 
Text Shadow

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".

Tip: The font-family property should hold several font names as a "fallback" system, to ensure maximum compatibility between browsers/operating systems. Start with the font you want, and end with a generic family (to let the browser pick a similar font in the generic family, if no other fonts are available). The font names should be separated with comma. Read more about fallback fonts in the .

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 Fonts

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

 

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".

Tip: The font-family property should hold several font names as a "fallback" system, to ensure maximum compatibility between browsers/operating systems. Start with the font you want, and end with a generic family (to let the browser pick a similar font in the generic family, if no other fonts are available). The font names should be separated with comma. Read more about fallback fonts in the .

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

 

 
Font Family

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.

p {
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)

Note: Before you publish your website, always check how your fonts appear on different browsers and devices, and always use !



Arial (sans-serif)

Arial is the most widely used font for both online and printed media. Arial is also the default font in Google Docs.

Arial is one of the safest web fonts, and it is available on all major operating systems.

Example

 

Lorem ipsum dolor sit amet.

0 1 2 3 4 5 6 7 8 9


Verdana (sans-serif)

Verdana is a very popular font. Verdana is easily readable even for small font sizes.

Example

 

Lorem ipsum dolor sit amet.

0 1 2 3 4 5 6 7 8 9


Tahoma (sans-serif)

The Tahoma font has less space between the characters.

Example

 

Lorem ipsum dolor sit amet.

0 1 2 3 4 5 6 7 8 9


Trebuchet MS (sans-serif)

Trebuchet MS was designed by Microsoft in 1996. Use this font carefully. Not supported by all mobile operating systems.

Example

 

Lorem ipsum dolor sit amet.

0 1 2 3 4 5 6 7 8 9


Times New Roman (serif)

Times New Roman is one of the most recognizable fonts in the world. It looks professional and is used in many newspapers and "news" websites. It is also the primary font for Windows devices and applications.

Example

 

Lorem ipsum dolor sit amet.

0 1 2 3 4 5 6 7 8 9


Georgia (serif)

Georgia is an elegant serif font. It is very readable at different font sizes, so it is a good candidate for mobile-responsive design.

Example

 

Lorem ipsum dolor sit amet.

0 1 2 3 4 5 6 7 8 9


Garamond (serif)

Garamond is a classical font used for many printed books. It has a timeless look and good readability.

Example

 

Lorem ipsum dolor sit amet.

0 1 2 3 4 5 6 7 8 9


Courier New (monospace)

Courier New is the most widely used monospace serif font. Courier New is often used with coding displays, and many email providers use it as their default font. Courier New is also the standard font for movie screenplays.

Example

 

Lorem ipsum dolor sit amet.

0 1 2 3 4 5 6 7 8 9


Brush Script MT (cursive)

The Brush Script MT font was designed to mimic handwriting. It is elegant and sophisticated, but can be hard to read. Use it carefully.

Example

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet.

0 1 2 3 4 5 6 7 8 9

Tip: Also check out all available and how to use them.

 

 
Font Web Safe

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 Code
"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 Code
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 Code
"Courier New", Courier, monospace

This is a Heading

This is a paragraph.

Cursive Fonts

font-family Example text Code
"Brush Script MT", cursive

This is a Heading

This is a paragraph.

Fantasy Fonts

font-family Example text Code
Copperplate, Papyrus, fantasy

This is a Heading

This is a paragraph.

Tip: Also check out all available and how to use them.


Font Fallbacks

CSS Font Style


Font Style

The font-style property is mostly used to specify italic text.

This property has three values:

  • normal - The text is shown normally
  • italic - The text is shown in italics
  • oblique - The text is "leaning" (oblique is very similar to italic, but less supported)

Example

p.normal {
  font-style: normal;
}

p.italic {
  font-style: italic;
}

p.oblique {
  font-style: oblique;
}

Font Weight

The font-weight property specifies the weight of a font:

Example

p.normal {
  font-weight: normal;
}

p.thick {
  font-weight: bold;
}

Font Variant

The font-variant property specifies whether or not a text should be displayed in a small-caps font.

In a small-caps font, all lowercase letters are converted to uppercase letters. However, the converted uppercase letters appears in a smaller font size than the original uppercase letters in the text.

Example

p.normal {
  font-variant: normal;
}

p.small {
  font-variant: small-caps;
}

Font Style

CSS Font Size

 

Font Size

The font-size property sets the size of the text.

Being able to manage the text size is important in web design. However, you should not use font size adjustments to make paragraphs look like headings, or headings look like paragraphs.

Always use the proper HTML tags, like

-

for headings and

for paragraphs.

The font-size value can be an absolute, or relative size.

Absolute size:

  • Sets the text to a specified size
  • Does not allow a user to change the text size in all browsers (bad for accessibility reasons)
  • Absolute size is useful when the physical size of the output is known

Relative size:

  • Sets the size relative to surrounding elements
  • Allows a user to change the text size in browsers

Note: If you do not specify a font size, the default size for normal text, like paragraphs, is 16px (16px=1em).


Set Font Size With Pixels

Setting the text size with pixels gives you full control over the text size:

Example

h1 {
  font-size: 40px;
}

h2 {
  font-size: 30px;
}

p {
  font-size: 14px;
}

Tip: If you use pixels, you can still use the zoom tool to resize the entire page.


Set Font Size With Em

To allow users to resize the text (in the browser menu), many developers use em instead of pixels.

1em is equal to the current font size. The default text size in browsers is 16px. So, the default size of 1em is 16px.

The size can be calculated from pixels to em using this formula: pixels/16=em

Example

h1 {
  font-size: 2.5em; /* 40px/16=2.5em */
}

h2 {
  font-size: 1.875em; /* 30px/16=1.875em */
}

p {
  font-size: 0.875em; /* 14px/16=0.875em */
}

In the example above, the text size in em is the same as the previous example in pixels. However, with the em size, it is possible to adjust the text size in all browsers.

Unfortunately, there is still a problem with older versions of Internet Explorer. The text becomes larger than it should when made larger, and smaller than it should when made smaller.



Use a Combination of Percent and Em

The solution that works in all browsers, is to set a default font-size in percent for the element:

Example

body {
  font-size: 100%;
}

h1 {
  font-size: 2.5em;
}

h2 {
  font-size: 1.875em;
}

p {
  font-size: 0.875em;
}

Our code now works great! It shows the same text size in all browsers, and allows all browsers to zoom or resize the text!


Responsive Font Size

The text size can be set with a vw unit, which means the "viewport width".

That way the text size will follow the size of the browser window:

Resize the browser window to see how the font size scales.

Example

 

Viewport is the browser window size. 1vw = 1% of viewport width. If the viewport is 50cm wide, 1vw is 0.5cm.

 

 
Font Size

CSS Google Fonts

 

Google Fonts

If you do not want to use any of the standard fonts in HTML, you can use Google Fonts.

Google Fonts are free to use, and have more than 1000 fonts to choose from.


How To Use Google Fonts

Just add a special style sheet link in the section and then refer to the font in the CSS.

Example

Here, we want to use a font named "Sofia" from Google Fonts:

Result:

Sofia Font

Lorem ipsum dolor sit amet.

123456790

Example

Here, we want to use a font named "Trirong" from Google Fonts:

Result:

Trirong Font

Lorem ipsum dolor sit amet.

123456790

Example

Here, we want to use a font named "Audiowide" from Google Fonts:

Result:

Audiowide Font

Lorem ipsum dolor sit amet.

123456790

Note: When specifying a font in CSS, always list at minimum one fallback font (to avoid unexpected behaviors). So, also here you should add a generic font family (like serif or sans-serif) to the end of the list.

For a list of all available Google Fonts, visit our .


Use Multiple Google Fonts

To use multiple Google fonts, just separate the font names with a pipe character (|), like this:

Example

Request multiple fonts:

Result:

Audiowide Font

Sofia Font

Trirong Font

Note: Requesting multiple fonts may slow down your web pages! So be careful about that.



Styling Google Fonts

Of course you can style Google Fonts as you like, with CSS!

Example

Style the "Sofia" font:


Result:
Sofia Font

Lorem ipsum dolor sit amet.

123456790


Enabling Font Effects

Google has also enabled different font effects that you can use.

First add effect=effectname to the Google API, then add a special class name to the element that is going to use the special effect. The class name always starts with font-effect- and ends with the effectname.

Example

Add the fire effect to the "Sofia" font:


Sofia on Fire
Result:

Sofia on Fire

To request multiple font effects, just separate the effect names with a pipe character (|), like this:

Example

Add multiple effects to the "Sofia" font:



Neon Effect


Outline Effect


Emboss Effect


Multiple Shadow Effect

Result:

Neon Effect

Outline Effect

Emboss Effect

Multiple Shadow Effect

 
Font Google

CSS Great Font Pairings


Great font pairings are essential to great design.


Font Pairing Rules

Here are some basic rules to create great font pairings:

1. Complement

It is always safe to find font pairings that complement one another.

A great font combination should harmonize, without being too similar or too different.

2. Use Font Superfamilies

A font superfamily is a set of fonts designed to work well together. So, using different fonts within the same superfamily is safe.

For example, the Lucida superfamily contains the following fonts: Lucida Sans, Lucida Serif, Lucida Typewriter Sans, Lucida Typewriter Serif and Lucida Math.

3. Contrast is King

Two fonts that are too similar will often conflict. However, contrasts, done the right way, brings out the best in each font.

Example: Combining serif with sans serif is a well known combination.

A strong superfamily includes both serif and sans serif variations of the same font (e.g. Lucida and Lucida Sans).

4. Choose Only One Boss

One font should be the boss. This establishes a hierarchy for the fonts on your page. This can be achieved by varying the size, weight and color.

Example

No doubt "Georgia" is the boss here:

body {
  background-color: black;
  font-family: Verdana, sans-serif;
  font-size: 16px;
  color: gray;
}

h1 {
  font-family: Georgia, serif;
  font-size: 60px;
  color: white;
}

Below, we have shown some popular font pairings that will suit many brands and contexts.



Georgia and Verdana

Georgia and Verdana is a classic combination. It also sticks to the web safe font standards:

Example

Use the "Georgia" font for headings, and "Verdana" for text:

Beautiful Norway

Norway has a total area of 385,252 square kilometers and a population of 5,438,657 (December 2020). Norway is bordered by Sweden, Finland and Russia to the north-east, and the Skagerrak to the south, with Denmark on the other side.

Norway has beautiful mountains, glaciers and stunning fjords. Oslo, the capital, is a city of green spaces and museums. Bergen, with colorful wooden houses, is the starting point for cruises to the dramatic Sognefjord. Norway is also known for fishing, hiking and skiing.


Helvetica and Garamond

Helvetica and Garamond is another classic combination that uses web safe fonts:

Example

Use the "Helvetica" font for headings, and "Garamond" for text:

Beautiful Norway

Norway has a total area of 385,252 square kilometers and a population of 5,438,657 (December 2020). Norway is bordered by Sweden, Finland and Russia to the north-east, and the Skagerrak to the south, with Denmark on the other side.

Norway has beautiful mountains, glaciers and stunning fjords. Oslo, the capital, is a city of green spaces and museums. Bergen, with colorful wooden houses, is the starting point for cruises to the dramatic Sognefjord. Norway is also known for fishing, hiking and skiing.


Popular Google Font Pairings

If you do not want to use standard fonts in HTML, you can use Google Fonts.

Google Fonts are free to use, and have more than 1000 fonts to choose from.

Below are some popular Google Web Font Pairings.


Merriweather and Open Sans

Example

Use the "Merriweather" font for headings, and "Open Sans" for text:

Beautiful Norway

Norway has a total area of 385,252 square kilometers and a population of 5,438,657 (December 2020). Norway is bordered by Sweden, Finland and Russia to the north-east, and the Skagerrak to the south, with Denmark on the other side.

Norway has beautiful mountains, glaciers and stunning fjords. Oslo, the capital, is a city of green spaces and museums. Bergen, with colorful wooden houses, is the starting point for cruises to the dramatic Sognefjord. Norway is also known for fishing, hiking and skiing.


Ubuntu and Lora

Example

Use the "Ubuntu" font for headings, and "Lora" for text:

Beautiful Norway

Norway has a total area of 385,252 square kilometers and a population of 5,438,657 (December 2020). Norway is bordered by Sweden, Finland and Russia to the north-east, and the Skagerrak to the south, with Denmark on the other side.

Norway has beautiful mountains, glaciers and stunning fjords. Oslo, the capital, is a city of green spaces and museums. Bergen, with colorful wooden houses, is the starting point for cruises to the dramatic Sognefjord. Norway is also known for fishing, hiking and skiing.


Abril Fatface and Poppins

Example

Use the "Abril Fatface" font for headings, and "Poppins" for text:

Beautiful Norway

Norway has a total area of 385,252 square kilometers and a population of 5,438,657 (December 2020). Norway is bordered by Sweden, Finland and Russia to the north-east, and the Skagerrak to the south, with Denmark on the other side.

Norway has beautiful mountains, glaciers and stunning fjords. Oslo, the capital, is a city of green spaces and museums. Bergen, with colorful wooden houses, is the starting point for cruises to the dramatic Sognefjord. Norway is also known for fishing, hiking and skiing.


Cinzel and Fauna One

Example

Use the "Cinzel" font for headings, and "Fauna One" for text:

Beautiful Norway

Norway has a total area of 385,252 square kilometers and a population of 5,438,657 (December 2020). Norway is bordered by Sweden, Finland and Russia to the north-east, and the Skagerrak to the south, with Denmark on the other side.

Norway has beautiful mountains, glaciers and stunning fjords. Oslo, the capital, is a city of green spaces and museums. Bergen, with colorful wooden houses, is the starting point for cruises to the dramatic Sognefjord. Norway is also known for fishing, hiking and skiing.


Fjalla One and Libre Baskerville

Example

Use the "Fjalla One" font for headings, and "Libre Baskerville" for text:

Beautiful Norway

Norway has a total area of 385,252 square kilometers and a population of 5,438,657 (December 2020). Norway is bordered by Sweden, Finland and Russia to the north-east, and the Skagerrak to the south, with Denmark on the other side.

Norway has beautiful mountains, glaciers and stunning fjords. Oslo, the capital, is a city of green spaces and museums. Bergen, with colorful wooden houses, is the starting point for cruises to the dramatic Sognefjord. Norway is also known for fishing, hiking and skiing.


Space Mono and Muli

Example

Use the "Space Mono" font for headings, and "Muli" for text:

Beautiful Norway

Norway has a total area of 385,252 square kilometers and a population of 5,438,657 (December 2020). Norway is bordered by Sweden, Finland and Russia to the north-east, and the Skagerrak to the south, with Denmark on the other side.

Norway has beautiful mountains, glaciers and stunning fjords. Oslo, the capital, is a city of green spaces and museums. Bergen, with colorful wooden houses, is the starting point for cruises to the dramatic Sognefjord. Norway is also known for fishing, hiking and skiing.


Spectral and Rubik

Example

Use the "Spectral" font for headings, and "Rubik" for text:

Beautiful Norway

Norway has a total area of 385,252 square kilometers and a population of 5,438,657 (December 2020). Norway is bordered by Sweden, Finland and Russia to the north-east, and the Skagerrak to the south, with Denmark on the other side.

Norway has beautiful mountains, glaciers and stunning fjords. Oslo, the capital, is a city of green spaces and museums. Bergen, with colorful wooden houses, is the starting point for cruises to the dramatic Sognefjord. Norway is also known for fishing, hiking and skiing.


Oswald and Noto Sans

Example

Use the "Oswald" font for headings, and "Noto Sans" for text:

Beautiful Norway

Norway has a total area of 385,252 square kilometers and a population of 5,438,657 (December 2020). Norway is bordered by Sweden, Finland and Russia to the north-east, and the Skagerrak to the south, with Denmark on the other side.

Norway has beautiful mountains, glaciers and stunning fjords. Oslo, the capital, is a city of green spaces and museums. Bergen, with colorful wooden houses, is the starting point for cruises to the dramatic Sognefjord. Norway is also known for fishing, hiking and skiing.

For a list of all free Google Fonts, visit our .


Font Pairings

CSS Font Property

 

The CSS Font Property

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

The font property is a shorthand property for:

  • font-style
  • font-variant
  • font-weight
  • font-size/line-height
  • font-family

Note: The font-size and font-family values are required. If one of the other values is missing, their default value are used.

Example

Use font to set several font properties in one declaration:

p.a {
  font: 20px Arial, sans-serif;
}

p.b {
  font: italic small-caps bold 12px/30px Georgia, serif;
}

Test Yourself With Exercises

Exercise:

Set the font for

to "Verdana".


 

 


All CSS Font Properties

Property Description
  Sets all the font properties in one declaration
  Specifies the font family for text
  Specifies the font size of text
  Specifies the font style for text
  Specifies whether or not a text should be displayed in a small-caps font
  Specifies the weight of a font

 

 
Font Shorthand

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 or ).

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 , sign in, and get a code to add in the section of your HTML page:

 

Read more about how to get started with Font Awesome in our .

Note: No downloading or installation is required!

Example


Result:
 

For a complete reference of all Font Awesome icons, visit our .



Bootstrap Icons

To use the Bootstrap glyphicons, add the following line inside the section of your HTML page:

 

Note: No downloading or installation is required!

Example


Google Icons

To use the Google icons, add the following line inside the section of your HTML page:

 

Note: No downloading or installation is required!

Example







cloud
favorite
attachment
computer
traffic


Result:

 

For a complete list of all icons, visit our .

 
CSS Icons

CSS Links

 

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



Styling Links

Links can be styled with any CSS property (e.g. color, font-family, background, etc.).

Example

a {
  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;
}

Example

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

auto

crosshair

default

e-resize

help

move

n-resize

ne-resize

nw-resize

pointer

progress

s-resize

se-resize

sw-resize

text

w-resize

wait

Test Yourself With Exercises

Exercise:

Set the color of links to "red".


This is a paragraph

  This is a link


 
CSS Links

CSS Lists


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 (
      ) - the list items are marked with bullets
    • ordered lists (
        ) - 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

      or
        :

        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

          or
            tag, affects the entire list, while properties added to the
          • 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

            More Examples


            This example demonstrates how to create a list with a red left border.


            This example demonstrates how to create a bordered list without bullets.


            This example demonstrates all the different list-item markers in CSS.


            Test Yourself With Exercises

            Exercise:

            Set the list style for unordered lists to "square".

            
            
            
            
            • Coffee
            • Tea
            • Coca Cola


            All CSS List Properties

            Property Description
            Sets all the properties for a list in one declaration
            Specifies an image as the list-item marker
            Specifies the position of the list-item markers (bullet points)
            Specifies the type of list-item marker

CSS Lists

CSS Tables

 

The look of an HTML table can be greatly improved with CSS:

Company Contact Country
Alfreds Futterkiste Maria Anders Germany
Berglunds snabbköp Christina Berglund Sweden
Centro comercial Moctezuma Francisco Chang Mexico
Ernst Handel Roland Mendel Austria
Island Trading Helen Bennett UK
Königlich Essen Philip Cramer Germany
Laughing Bacchus Winecellars Yoshi Tannamuri Canada
Magazzini Alimentari Riuniti Giovanni Rovelli Italy

 


Table Borders

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

The example below specifies a solid border for ,

, and elements:

 

Firstname Lastname
Peter Griffin
Lois Griffin

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 element:

 

Firstname Lastname
Peter Griffin
Lois Griffin

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

and 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
Peter Griffin
Lois Griffin

Example

table {
  border-collapse: collapse;
}

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

 

Firstname Lastname
Peter Griffin
Lois Griffin

Example

table {
  border: 1px solid;
}

 
CSS Tables

CSS Tables


The look of an HTML table can be greatly improved with CSS:

Company Contact Country
Alfreds Futterkiste Maria Anders Germany
Berglunds snabbköp Christina Berglund Sweden
Centro comercial Moctezuma Francisco Chang Mexico
Ernst Handel Roland Mendel Austria
Island Trading Helen Bennett UK
Königlich Essen Philip Cramer Germany
Laughing Bacchus Winecellars Yoshi Tannamuri Canada
Magazzini Alimentari Riuniti Giovanni Rovelli Italy

 


Table Borders

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

The example below specifies a solid border for ,

, and elements:

 

Firstname Lastname
Peter Griffin
Lois Griffin

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 element:

 

Firstname Lastname
Peter Griffin
Lois Griffin

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

and 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
Peter Griffin
Lois Griffin

Example

table {
  border-collapse: collapse;
}

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

 

Firstname Lastname
Peter Griffin
Lois Griffin

Example

table {
  border: 1px solid;
}

 
Table Borders

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 elements to 70px:

Firstname Lastname Savings
Peter Griffin $100
Lois Griffin $150
Joe Swanson $300

Example

table {
  width: 100%;
}

th {
  height: 70px;
}

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

Firstname Lastname Savings
Peter Griffin $100
Lois Griffin $150
Joe Swanson $300

Example

table {
  width: 50%;
}

Table Size

CSS Table Alignment


Horizontal Alignment

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

By default, the content of elements are center-aligned and the content of elements are left-aligned.

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

Firstname Lastname Savings
Peter Griffin $100
Lois Griffin $150
Joe Swanson $300

Example

td {
  text-align: center;
}

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

Firstname Lastname Savings
Peter Griffin $100
Lois Griffin $150
Joe Swanson $300

Example

th {
  text-align: left;
}

Vertical Alignment

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

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

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

Firstname Lastname Savings
Peter Griffin $100
Lois Griffin $150
Joe Swanson $300

Example

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

Table Alignment

CSS Table Style


Table Padding

To control the space between the border and the content in a table, use the padding property on and elements:

First Name Last Name Savings
Peter Griffin $100
Lois Griffin $150
Joe Swanson $300

Example

th, td {
  padding: 15px;
  text-align: left;
}

Horizontal Dividers

First Name Last Name Savings
Peter Griffin $100
Lois Griffin $150
Joe Swanson $300

Add the border-bottom property to and for horizontal dividers:

Example

th, td {
  border-bottom: 1px solid #ddd;
}

Hoverable Table

Use the :hover selector on to highlight table rows on mouse over:

First Name Last Name Savings
Peter Griffin $100
Lois Griffin $150
Joe Swanson $300

Example

tr:hover {background-color: coral;}


Striped Tables

First Name Last Name Savings
Peter Griffin $100
Lois Griffin $150
Joe Swanson $300

For zebra-striped tables, use the nth-child() selector and add a background-color to all even (or odd) table rows:

Example

tr:nth-child(even) {background-color: #f2f2f2;}

Table Color

The example below specifies the background color and text color of elements:

First Name Last Name Savings
Peter Griffin $100
Lois Griffin $150
Joe Swanson $300

Example

th {
  background-color: #04AA6D;
  color: white;
}

Table Style

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 Points Points Points
Jill Smith 50 50 50 50 50 50 50 50 50 50 50 50
Eve Jackson 94 94 94 94 94 94 94 94 94 94 94 94
Adam Johnson 67 67 67 67 67 67 67 67 67 67 67 67

Add a container element (like

) with overflow-x:auto around the element to make it responsive:

 

Example

 

... table content ...


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


More Examples


This example demonstrates how to create a fancy table.


This example demonstrates how to position the table caption.


Test Yourself With Exercises

Exercise:

Set the border to "2px solid green" for table, th and td elements.

 
Firstname Lastname
Peter Griffin
Lois Griffin
 


CSS Table Properties

Property Description
  Sets all the border properties in one declaration
  Specifies whether or not table borders should be collapsed
  Specifies the distance between the borders of adjacent cells
  Specifies the placement of a table caption
  Specifies whether or not to display borders and background on empty cells in a table
  Sets the layout algorithm to be used for a table
 
Table Responsive

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

This panel contains a

element, which is hidden by default (display: none).

It is styled with CSS, and we use JavaScript to show it (change it to (display: block).


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
element is a block-level element.

Examples of block-level elements:


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 element inside a paragraph.

Examples of inline elements:


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

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

More Examples


This example demonstrates display: none; versus visibility: hidden;


This example demonstrates how to use CSS and JavaScript to show an element on click.


Test Yourself With Exercises

Exercise:

Hide the

CSS Display/Visibility Properties

Property Description
Specifies how an element should be displayed
Specifies whether or not an element should be visible

CSS Display

CSS Layout - width and max-width

 

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
element has a width of 500px, and margin set to auto.

Note: The problem with the

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
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 Max-width
 

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
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
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 scrollep: 0;ition

CSS Position

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:

Example

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

Note: z-index only works on (position: absolute, position: relative, position: fixed, or position: sticky) and (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:

 
Black box

 
Gray box

 
Green box





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:



 
Black box

 
Gray box

 
Green box





Test Yourself With Exercises

Exercise:

Both the header and the paragraph are positioned at the top of the page.

Make sure that the header is placed on top of the paragraph.

  

 CSS Property

Property Description
Sets the stack order of an element

CSS Z-index

CSS Layout - Overflow


The CSS overflow property controls what happens to content that is too big to fit into an area.

This text is really long and the height of its container is only 100 pixels. Therefore, a scrollbar is added to help the reader to scroll the content. 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. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem.


CSS Overflow

The overflow property specifies whether to clip the content or to add scrollbars when the content of an element is too big to fit in the specified area.

The overflow property has the following values:

  • visible - Default. The overflow is not clipped. The content renders outside the element's box
  • hidden - The overflow is clipped, and the rest of the content will be invisible
  • scroll - The overflow is clipped, and a scrollbar is added to see the rest of the content
  • auto - Similar to scroll, but it adds scrollbars only when necessary

Note: The overflow property only works for block elements with a specified height.

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


overflow: visible

By default, the overflow is visible, meaning that it is not clipped and it renders outside the element's box:

You can use the overflow property when you want to have better control of the layout. The overflow property specifies what happens if content overflows an element's box.

Example

div {
  width: 200px;
  height: 65px;
  background-color: coral;
  overflow: visible;
}


overflow: hidden

With the hidden value, the overflow is clipped, and the rest of the content is hidden:

Example

div {
  overflow: hidden;
}

overflow: scroll

Setting the value to scroll, the overflow is clipped and a scrollbar is added to scroll inside the box. Note that this will add a scrollbar both horizontally and vertically (even if you do not need it):

You can use the overflow property when you want to have better control of the layout. The overflow property specifies what happens if content overflows an element's box.

Example

div {
  overflow: scroll;
}

overflow: auto

The auto value is similar to scroll, but it adds scrollbars only when necessary:

You can use the overflow property when you want to have better control of the layout. The overflow property specifies what happens if content overflows an element's box.

Example

div {
  overflow: auto;
}

overflow-x and overflow-y

The overflow-x and overflow-y properties specifies whether to change the overflow of content just horizontally or vertically (or both):

overflow-x specifies what to do with the left/right edges of the content.
overflow-y specifies what to do with the top/bottom edges of the content.

You can use the overflow property when you want to have better control of the layout. The overflow property specifies what happens if content overflows an element's box.

Example

div {
  overflow-x: hidden; /* Hide horizontal scrollbar */
  overflow-y: scroll; /* Add vertical scrollbar */
}

Test Yourself With Exercises

Exercise:

Force a scroll bar to the

element with class="intro".





Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Phasellus imperdiet, nulla et dictum interdum,
nisi lorem egestas odio,
vitae scelerisque enim ligula venenatis dolor.


All CSS Overflow Properties

Property Description
Specifies what happens if content overflows an element's box
Specifies whether or not the browser can break lines with long words, if they overflow its container
Specifies what to do with the left/right edges of the content if it overflows the element's content area
Specifies what to do with the top/bottom edges of the content if it overflows the element's content area


CSS Overflow

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 Float

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:

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: left;
}

Example - No float

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

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

 

 
Float

CSS Layout - clear and clearfix


The clear Property

When we use the float property, and we want the next element below (not on right or left), we will have to use the clear property.

The clear property specifies what should happen with the element that is next to a floating element.

The clear property can have one of the following values:

  • none - The element is not pushed below left or right floated elements. This is default
  • left - The element is pushed below left floated elements
  • right - The element is pushed below right floated elements
  • both - The element is pushed below both left and right floated elements
  • inherit - The element inherits the clear value from its parent

When clearing floats, you should match the clear to the float: If an element is floated to the left, then you should clear to the left. Your floated element will continue to float, but the cleared element will appear below it on the web page.

Example

This example clears the float to the left. Here, it means that the element is pushed below the left floated element: 

div1 {
  float: left;
}

div2 {
  clear: left;
}

The clearfix Hack

If a floated element is taller than the containing element, it will "overflow" outside of its container. We can then add a clearfix hack to solve this problem:

Example

.clearfix {
  overflow: auto;
}

The overflow: auto clearfix works well as long as you are able to keep control of your margins and padding (else you might see scrollbars). The new, modern clearfix hack however, is safer to use, and the following code is used for most webpages:

Example

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

You will learn more about the ::after pseudo-element in a later chapter.


Clear

CSS Layout - Float Examples

 

This page contains common float examples.


Grid of Boxes / Equal Width Boxes

Box 1

Box 2

 

Box 1

Box 2

Box 3

With the float property, it is easy to float boxes of content side by side:

Example

* {
  box-sizing: border-box;
}

.box {
  float: left;
  width: 33.33%; /* three boxes (use 25% for four, and 50% for two, etc) */
  padding: 50px; /* if you want space between the images */
}

What is box-sizing?

You can easily create three floating boxes side by side. However, when you add something that enlarges the width of each box (e.g. padding or borders), the box will break. The box-sizing property allows us to include the padding and border in the box's total width (and height), making sure that the padding stays inside of the box and that it does not break.

You can read more about the box-sizing property in our .


Images Side By Side

 
 

The grid of boxes can also be used to display images side by side:

Example

.img-container {
  float: left;
  width: 33.33%; /* three containers (use 25% for four, and 50% for two, etc) */
  padding: 5px; /* if you want space between the images */
}


Equal Height Boxes

In the previous example, you learned how to float boxes side by side with an equal width. However, it is not easy to create floating boxes with equal heights. A quick fix however, is to set a fixed height, like in the example below:

Box 1

Some content, some content, some content

Box 2

Some content, some content, some content

Some content, some content, some content

Some content, some content, some content

Example

.box {
  height: 500px;
}

However, this is not very flexible. It is ok if you can guarantee that the boxes will always have the same amount of content in them. But many times, the content is not the same. If you try the example above on a mobile phone, you will see that the second box's content will be displayed outside of the box. This is where CSS3 Flexbox comes in handy - as it can automatically stretch boxes to be as long as the longest box:

Example

Using Flexbox to create flexible boxes:

Box 1 - This is some text to make sure that the content gets really tall. This is some text to make sure that the content gets really tall. This is some text to make sure that the content gets really tall.
Box 2 - My height will follow Box 1.

Tip:  You can read more about the Flexbox Layout Module in our .


Navigation Menu

You can also use float with a list of hyperlinks to create a horizontal menu:

Example


Web Layout Example

It is also common to do entire web layouts using the float property:

Example

.header, .footer {
  background-color: grey;
  color: white;
  padding: 15px;
}

.column {
  float: left;
  padding: 15px;
}

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

.menu {
  width: 25%;
}

.content {
  width: 75%;
}

More Examples


Let an image float to the right in a paragraph. Add border and margins to the image.


Let an image with a caption float to the right.


Let the first letter of a paragraph float to the left and style the letter.


Use float to create a homepage with a navbar, header, footer, left content and main content.


All CSS Float Properties

Property Description
  Defines how the width and height of an element are calculated: should they include padding and borders, or not
  Specifies what should happen with the element that is next to a floating element
  Specifies whether an element should float to the left, right, or not at all
  Specifies what happens if content overflows an element's box
  Specifies what to do with the left/right edges of the content if it overflows the element's content area
  Specifies what to do with the top/bottom edges of the content if it overflows the element's content area

 

 
Float Examples

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: inline, display: 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 Inline-block

CSS Layout - Horizontal & Vertical Align

 

 

Center elements
horizontally and vertically


Center Align Elements

To horizontally center a block element (like

), 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:

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;

Example

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

Tip: For more examples on how to align text, see the chapter.



Center an Image

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

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;:

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

With Clearfix

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:

Example

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

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

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:

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:

Example

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

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

Tip: You will learn more about the transform property in our .


Center Vertically - Using Flexbox

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

Example

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

Tip: You will learn more about Flexbox in our .


Test Yourself With Exercises

Exercise:

Use the margin property to make sure that the

element is center aligned according to its parent element.

 




Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Phasellus imperdiet, nulla et dictum interdum,
nisi lorem egestas odio,
vitae scelerisque enim ligula venenatis dolor.
 


 
CSS Align

CSS Combinators

 

CSS Combinators

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

elements inside

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

elements that are children of a

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

element that are placed immediately after

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

elements that are next siblings of

elements: 

 

Example

div ~ p {
  background-color: yellow;
}

Test Yourself With Exercises

Exercise:

Change the color of all

elements, that are descendants of

elements, to "red".
 

 


All CSS Combinator Selectors

Selector Example Example description
  div p Selects all

elements inside

elements
  div > p Selects all

elements where the parent is a

element
  div + p Selects the first

element that are placed immediately after

elements
  p ~ ul Selects every
  • element that are preceded by a

element


 
CSS Combinators

CSS Pseudo-classes

 

What are Pseudo-classes?

A pseudo-class is used to define a special state of an element.

For example, it can be used to:

  • Style an element when a user mouses over it
  • Style visited and unvisited links differently
  • Style an element when it gets focus

Mouse Over Me

 


Syntax

The syntax of pseudo-classes:

selector:pseudo-class {
  property: value;
}

Anchor Pseudo-classes

Links can be displayed in different ways:

Example

/* unvisited link */
a:link {
  color: #FF0000;
}

/* visited link */
a:visited {
  color: #00FF00;
}

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

/* selected link */
a:active {
  color: #0000FF;
}

Note: a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective! a:active MUST come after a:hover in the CSS definition in order to be effective! Pseudo-class names are not case-sensitive.



Pseudo-classes and HTML Classes

Pseudo-classes can be combined with HTML classes:

When you hover over the link in the example, it will change color:

Example

a.highlight:hover {
  color: #ff0000;
}

Hover on

 

An example of using the :hover pseudo-class on a

element:

 

Example

div:hover {
  background-color: blue;
}

Simple Tooltip Hover

Hover over a

element to show a

element (like a tooltip):

Hover over me to show the

element.

Tada! Here I am!

Example

p {
  display: none;
  background-color: yellow;
  padding: 20px;
}

div:hover p {
  display: block;
}

CSS - The :first-child Pseudo-class

The :first-child pseudo-class matches a specified element that is the first child of another element.

Match the first

element

In the following example, the selector matches any

element that is the first child of any element:

Example

p:first-child {
  color: blue;
}

Match the first element in all

elements

In the following example, the selector matches the first element in all

elements:

Example

p i:first-child {
  color: blue;
}

Match all elements in all first child

elements

In the following example, the selector matches all elements in

elements that are the first child of another element:

Example

p:first-child i {
  color: blue;
}

CSS - The :lang Pseudo-class

The :lang pseudo-class allows you to define special rules for different languages.

In the example below, :lang defines the quotation marks for elements with lang="no":

Example


Some text A quote in a paragraph Some text.




More Examples


This example demonstrates how to add other styles to hyperlinks.


This example demonstrates how to use the :focus pseudo-class.


Test Yourself With Exercises

Exercise:

Set the background-color to red, when you mouse over a link.

 


All CSS Pseudo Classes

Selector Example Example description
  a:active Selects the active link
  input:checked Selects every checked element
  input:disabled Selects every disabled element
  p:empty Selects every

element that has no children

  input:enabled Selects every enabled element
  p:first-child Selects every

elements that is the first child of its parent

  p:first-of-type Selects every

element that is the first

element of its parent

  input:focus Selects the element that has focus
  a:hover Selects links on mouse over
  input:in-range Selects elements with a value within a specified range
  input:invalid Selects all elements with an invalid value
  p:lang(it) Selects every

element with a lang attribute value starting with "it"

  p:last-child Selects every

elements that is the last child of its parent

  p:last-of-type Selects every

element that is the last

element of its parent

  a:link Selects all unvisited links
  :not(p) Selects every element that is not a

element

  p:nth-child(2) Selects every

element that is the second child of its parent

  p:nth-last-child(2) Selects every

element that is the second child of its parent, counting from the last child

  p:nth-last-of-type(2) Selects every

element that is the second

element of its parent, counting from the last child

  p:nth-of-type(2) Selects every

element that is the second

element of its parent

  p:only-of-type Selects every

element that is the only

element of its parent

  p:only-child Selects every

element that is the only child of its parent

  input:optional Selects elements with no "required" attribute
  input:out-of-range Selects elements with a value outside a specified range
  input:read-only Selects elements with a "readonly" attribute specified
  input:read-write Selects elements with no "readonly" attribute
  input:required Selects elements with a "required" attribute specified
  root Selects the document's root element
  #news:target Selects the current active #news element (clicked on a URL containing that anchor name)
  input:valid Selects all elements with a valid value
  a:visited Selects all visited links

All CSS Pseudo Elements

Selector Example Example description
  p::after Insert content after every

element

  p::before Insert content before every

element

  p::first-letter Selects the first letter of every

element

  p::first-line Selects the first line of every

element

  ::marker Selects the markers of list items
  p::selection Selects the portion of an element that is selected by a user

 
CSS Pseudo-class

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

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

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

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

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 ::selection: color, background, cursor, and outline.

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

Example

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

Test Yourself With Exercises

Exercise:

Set the background-color to red, of the first line of the paragraph.




In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since. 'Whenever you feel like criticizing anyone,' he told me, 'just remember that all the people in this world haven't had the advantages that you've had.'




 


All CSS Pseudo Elements

Selector Example Example description
  p::after Insert something after the content of each

element

  p::before Insert something before the content of each

element

  p::first-letter Selects the first letter of each

element

  p::first-line Selects the first line of each

element

  ::marker Selects the markers of list items
  p::selection Selects the portion of an element that is selected by a user

All CSS Pseudo Classes

Selector Example Example description
  a:active Selects the active link
  input:checked Selects every checked element
  input:disabled Selects every disabled element
  p:empty Selects every

element that has no children

  input:enabled Selects every enabled element
  p:first-child Selects every

elements that is the first child of its parent

  p:first-of-type Selects every

element that is the first

element of its parent

  input:focus Selects the element that has focus
  a:hover Selects links on mouse over
  input:in-range Selects elements with a value within a specified range
  input:invalid Selects all elements with an invalid value
  p:lang(it) Selects every

element with a lang attribute value starting with "it"

  p:last-child Selects every

elements that is the last child of its parent

  p:last-of-type Selects every

element that is the last

element of its parent

  a:link Selects all unvisited links
  :not(p) Selects every element that is not a

element

  p:nth-child(2) Selects every

element that is the second child of its parent

  p:nth-last-child(2) Selects every

element that is the second child of its parent, counting from the last child

  p:nth-last-of-type(2) Selects every

element that is the second

element of its parent, counting from the last child

  p:nth-of-type(2) Selects every

element that is the second

element of its parent

  p:only-of-type Selects every

element that is the only

element of its parent

  p:only-child Selects every

element that is the only child of its parent

  input:optional Selects elements with no "required" attribute
  input:out-of-range Selects elements with a value outside a specified range
  input:read-only Selects elements with a "readonly" attribute specified
  input:read-write Selects elements with no "readonly" attribute
  input:required Selects elements with a "required" attribute specified
  root Selects the document's root element
  #news:target Selects the current active #news element (clicked on a URL containing that anchor name)
  input:valid Selects all elements with a valid value
  a:visited Selects all visited links

 

 
CSS Pseudo-element

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


opacity 0.5

opacity 1
(default)

Example

img {
  opacity: 0.5;
}

Transparent Hover Effect

The opacity property is often used together with the :hover selector to change the opacity on mouse-over:

Example
img {
  opacity: 0.5;
}

img:hover {
  opacity: 1.0;
}

Example explained

The first CSS block is similar to the code in Example 1. In addition, we have added what should happen when a user hovers over one of the images. In this case we want the image to NOT be transparent when the user hovers over it. The CSS for this is opacity:1;.

When the mouse pointer moves away from the image, the image will be transparent again.

An example of reversed hover effect:

 
 

Example

img:hover {
  opacity: 0.5;
}


Transparent Box

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:

opacity 1

opacity 0.6

opacity 0.3

opacity 0.1

Example

div {
  opacity: 0.3;
}

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

You learned from our , that you can use RGB as a color value. In addition to RGB, you can use an RGB color value with an alpha channel (RGBA) - which specifies the opacity for a color.

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).

Tip: You will learn more about RGBA Colors in our .

Example

div {
  background: rgba(76, 175, 80, 0.3) /* Green background with 30% opacity */
}

Text in Transparent Box

This is some text that is placed in the transparent box.

Example

    

This is some text that is placed in the transparent box.



First, we create a

element (class="background") with a background image, and a border.

 

Then we create another

(class="transbox") inside the first
.

 

The

have a background color, and a border - the div is transparent.

 

Inside the transparent

, we add some text inside a

element.


Test Yourself With Exercises

Exercise:

Use CSS to set the transparency of the image to 50%.




 


 
CSS Opacity

CSS Navigation Bar


Demo: Navigation Bars





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

    and
  • elements makes perfect sense:

    Example


    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 Navigation Bar

CSS Navigation Bar

 

Demo: Navigation Bars


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

  • and
  • elements makes perfect sense:

     

    Example





    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.


     
Navbar

CSS Vertical Navigation Bar

 

Vertical Navigation Bar

 

To build a vertical navigation bar, you can style the 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

, and remove the width of , 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:

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:

Example

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

Center Links & Add Borders

Add text-align:center to

Vertical Navbar

CSS Horizontal Navigation Bar

 

Horizontal Navigation Bar

 

  •  

There are two ways to create a horizontal navigation bar. Using inline or floating list items.

Inline List Items

One way to build a horizontal navigation bar is to specify the

  • elements as inline, in addition to the "standard" code from the previous page:

     

    Example

    li {
      display: inline;
    }

    Example explained:

    • display: inline; - By default,
    • elements are block elements. Here, we remove the line breaks before and after each list item, to display them on one line

    Floating List Items

    Another way of creating a horizontal navigation bar is to float the

  • elements, and specify a layout for the navigation links:

     

    Example

    li {
      float: left;
    }

    a {
      display: block;
      padding: 8px;
      background-color: #dddddd;
    }

    Example explained:

    • float: left; - Use float to get block elements to float next to each other
    • display: block; - Allows us to specify padding (and height, width, margins, etc. if you want)
    • padding: 8px; - Specify some padding between each element, to make them look good

    Tip: Add the background-color to

    instead of each element if you want a full-width background color:

    Example

    ul {
      background-color: #dddddd;
    }

    Horizontal Navigation Bar Examples

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

    Example

    ul {
      list-style-type: none;
      margin: 0;
      padding: 0;
      overflow: hidden;
      background-color: #333;
    }

    li {
      float: left;
    }

    li a {
      display: block;
      color: white;
      text-align: center;
      padding: 14px 16px;
      text-decoration: none;
    }

    /* Change the link color to #111 (black) on hover */
    li a:hover {
      background-color: #111;
    }

    Active/Current Navigation Link

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

    Example

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

    Right-Align Links

    Right-align links by floating the list items to the right (float:right;):

    Border Dividers

    Add the border-right property to

    • to create link dividers:

       

      •  

      Example

      /* Add a gray right border to all list items, except the last item (last-child) */
      li {
        border-right: 1px solid #bbb;
      }

      li:last-child {
        border-right: none;
      }

      Fixed Navigation Bar

      Make the navigation bar stay at the top or the bottom of the page, even when the user scrolls the page:

      Fixed Top

      ul {
        position: fixed;
        top: 0;
        width: 100%;
      }

      Fixed Bottom

      ul {
        position: fixed;
        bottom: 0;
        width: 100%;
      }

      Note: Fixed position might not work properly on mobile devices.

      Gray Horizontal Navbar

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

       

      Example

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

      li a {
        color: #666;
      }

      Sticky Navbar

      Add position: sticky; to

      • to create a sticky navbar.

       

      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).

      Example

      ul {
        position: -webkit-sticky; /* Safari */
        position: sticky;
        top: 0;
      }

      Note: Internet Explorer do not support sticky positioning. Safari requires a -webkit- prefix (see example above). You must also specify at least one of top, right, bottom or left for sticky positioning to work.



      More Examples

      Responsive Topnav

      How to use CSS media queries to create a responsive top navigation.

       

      Responsive Sidenav

      How to use CSS media queries to create a responsive side navigation.

       

      Dropdown Navbar

      How to add a dropdown menu inside a navigation bar.

       

      Ever heard about W3Schools Spaces? Here you can create your website from scratch or use a template, and host it for free.

      * no credit card required


Horizontal Navbar

CSS Dropdowns

 

Create a hoverable dropdown with CSS.


Demo: Dropdown Examples

Move the mouse over the examples below:

 


Basic Dropdown

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

Example


   Mouse over me
 

Example Explained

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

 

Use a container element (like

) to create the dropdown content and add whatever you want inside of it.

 

Wrap a

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:

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




Right-aligned Dropdown Content

 

If you want the dropdown menu to go from right to left, instead of left to right, add right: 0;

Example

.dropdown-content {
  right: 0;
}

More Examples

Dropdown Image

How to add an image and other content inside the dropdown box.

Hover over the image:

Dropdown Navbar

How to add a dropdown menu inside a navigation bar.

 

 

 
CSS Dropdowns

CSS Image Gallery

 
 

Image Gallery

The following image gallery is created with CSS:

Example 

 
 
 

More Examples

Responsive Image Gallery

How to use CSS media queries to create a responsive image gallery that will look good on desktops, tablets and smart phones.

 
CSS Image Gallery

CSS Image Sprites

 

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:

  •  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 Image Sprites
 

Style HTML Elements With Specific Attributes

It is possible to style HTML elements that have specific attributes or attribute values.


CSS [attribute] Selector

The [attribute] selector is used to select elements with a specified attribute.

The following example selects all elements with a target attribute:

Example

a[target] {
  background-color: yellow;
}

CSS [attribute="value"] Selector

The [attribute="value"] selector is used to select elements with a specified attribute and value.

The following example selects all elements with a target="_blank" attribute:

Example

a[target="_blank"] {
  background-color: yellow;
}

CSS [attribute~="value"] Selector

The [attribute~="value"] selector is used to select elements with an attribute value containing a specified word.

The following example selects all elements with a title attribute that contains a space-separated list of words, one of which is "flower":

Example

[title~="flower"] {
  border: 5px solid yellow;
}

The example above will match elements with title="flower", title="summer flower", and title="flower new", but not title="my-flower" or title="flowers".



CSS [attribute|="value"] Selector

The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-).

Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text".

Example

[class|="top"] {
  background: yellow;
}

CSS [attribute^="value"] Selector

The [attribute^="value"] selector is used to select elements with the specified attribute, whose value starts with the specified value.

The following example selects all elements with a class attribute value that starts with "top":

Note: The value does not have to be a whole word!

Example

[class^="top"] {
  background: yellow;
}

CSS [attribute$="value"] Selector

The [attribute$="value"] selector is used to select elements whose attribute value ends with a specified value.

The following example selects all elements with a class attribute value that ends with "test":

Note: The value does not have to be a whole word!  

Example

[class$="test"] {
  background: yellow;
}

CSS [attribute*="value"] Selector

The [attribute*="value"] selector is used to select elements whose attribute value contains a specified value.

The following example selects all elements with a class attribute value that contains "te":

Note: The value does not have to be a whole word!  

Example

[class*="te"] {
  background: yellow;
}

Styling Forms

The attribute selectors can be useful for styling forms without class or ID:

Example

input[type="text"] {
  width: 150px;
  display: block;
  margin-bottom: 10px;
  background-color: yellow;
}

input[type="button"] {
  width: 120px;
  margin-left: 35px;
  display: block;
}

Tip: Visit our for more examples on how to style forms with CSS.


Test Yourself With Exercises


All CSS Attribute Selectors

Selector Example Example description
  [target] Selects all elements with a target attribute
  [target="_blank"] Selects all elements with target="_blank"
  [title~="flower"] Selects all elements with a title attribute that contains a space-separated list of words, one of which is "flower"
  [lang|="en"] Selects all elements with a lang attribute value starting with "en"
  a[href^="https"] Selects all elements with a href attribute value starting with "https"
  a[href$=".pdf"] Selects all elements with a href attribute value ending with ".pdf"
  a[href*="w3schools"] Selects all elements with a href attribute value containing the substring "w3schools"

 

 
CSS Attr Selectors

CSS Forms


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


Styling Input Fields

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

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:

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.
Read more about the box-sizing property in our chapter.


Bordered Inputs

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

Example

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

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

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. You will learn more about the transition property later, in our chapter.

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

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 */

For more information about how to style buttons with CSS, read our .


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.

Advanced: The following example uses to create a responsive form. You will learn more about this in a later chapter.



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
Used with the ::before and ::after pseudo-elements, to insert generated content
Increments one or more counter values
Creates or resets one or more counters
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

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

 

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.

Tip: To create a 2-column layout, change the width to 50%. To create a 4-column layout, use 25%, etc.

Tip: Do you wonder how the @media rule works? .

Tip: A more modern way of creating column layouts, is to use CSS Flexbox. However, it is not supported in Internet Explorer 10 and earlier versions. If you require IE6-10 support, use floats (as shown above).

To learn more about the Flexible Box Layout Module, .


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:

 

Ever heard about W3Schools Spaces? Here you can create your website from scratch or use a template, and host it for free.

* no credit card required

 
CSS Website Layout

CSS Units

 

CSS Units

CSS has several different units for expressing a length.

Many CSS properties take "length" values, such as width, margin, padding, font-size, etc.

Length is a number followed by a length unit, such as 10px, 2em, etc.

Example

Set different length values, using px (pixels):

h1 {
  font-size: 60px;
}

p {
  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)  
ex Relative to the x-height of the current font (rarely used)  
ch Relative to width of the "0" (zero)  
rem Relative to font-size of the root element  
vw Relative to 1% of the width of the viewport*  
vh Relative to 1% of the height of the viewport*  
vmin Relative to 1% of viewport's* smaller dimension  
vmax Relative to 1% of viewport's* larger dimension  
% Relative to the parent element  

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.



Browser Support

The numbers in the table specify the first browser version that fully supports the length unit.

Length Unit          
em, ex, %, px, cm, mm, in, pt, pc 1.0 3.0 1.0 1.0 3.5
ch 27.0 9.0 1.0 7.0 20.0
rem 4.0 9.0 3.6 4.1 11.6
vh, vw 20.0 9.0 19.0 6.0 20.0
vmin 20.0 12.0 19.0 6.0 20.0
vmax 26.0 16.0 19.0 7.0 20.0



 
CSS Units

CSS Specificity

 

What is Specificity?

If there are two or more CSS rules that point to the same element, the selector with the highest specificity value will "win", and its style declaration will be applied to that HTML element.

Think of specificity as a score/rank that determines which style declaration is ultimately applied to an element.

Look at the following examples:

Example 1

In this example, we have used the "p" element as selector, and specified a red color for this element. The text will be red:

 

Now, look at example 2:

Example 2

In this example, we have added a class selector (named "test"), and specified a green color for this class. The text will now be green (even though we have specified a red color for the element selector "p"). This is because the class selector is given higher priority:

 

Example 3

In this example, we have added the id selector (named "demo"). The text will now be blue, because the id selector is given higher priority:

 

Example 4

In this example, we have added an inline style for the "p" element. The text will now be pink, because the inline style is given the highest priority:

 


Specificity Hierarchy

Every CSS selector has its place in the specificity hierarchy.

There are four categories which define the specificity level of a selector:

  1. Inline styles - Example:

     

  2. IDs - Example: #navbar
  3. Classes, pseudo-classes, attribute selectors - Example: .test, :hover, [href]
  4. Elements and pseudo-elements - Example: h1, ::before

How to Calculate Specificity?

Memorize how to calculate specificity!

Start at 0, add 100 for each ID value, add 10 for each class value (or pseudo-class or attribute selector), add 1 for each element selector or pseudo-element.

Note: Inline style gets a specificity value of 1000, and is always given the highest priority!

Note 2: There is one exception to this rule: if you use the rule, it will even override inline styles!

The table below shows some examples on how to calculate specificity values:

Selector Specificity Value Calculation
p 1 1
p.test 11 1 + 10
p#demo 101 1 + 100

 

1000 1000
#demo 100 100
.test 10 10
p.test1.test2 21 1 + 10 + 10
#navbar p#demo 201 100 + 1 + 100
* 0 0 (the universal selector is ignored)

The selector with the highest specificity value will win and take effect!

Consider these three code fragments:

Example

A: h1
B: h1#content

 

The specificity of A is 1 (one element selector)
The specificity of B is 101 (one ID reference + one element selector)
The specificity of C is 1000 (inline styling)

Since the third rule (C) has the highest specificity value (1000), this style declaration will be applied.



More Specificity Rules Examples

Equal specificity: the latest rule wins - If the same rule is written twice into the external style sheet, then the latest rule wins:

Example

h1 {background-color: yellow;}
h1 {background-color: red;}

 


ID selectors have a higher specificity than attribute selectors - Look at the following three code lines:

Example

div#a {background-color: green;}
#a {background-color: yellow;}
div[id=a] {background-color: blue;}

 

the first rule is more specific than the other two, and will therefore be applied.


Contextual selectors are more specific than a single element selector - The embedded style sheet is closer to the element to be styled. So in the following situation

Example

From external CSS file:
#content h1 {background-color: red;}

In HTML file:

the latter rule will be applied.


A class selector beats any number of element selectors - a class selector such as .intro beats h1, p, div, etc:

Example

.intro {background-color: yellow;}
h1 {background-color: red;}

 


The universal selector (*) and inherited values have a specificity of 0 - The universal selector (*) and inherited values are ignored!

CSS Specificity

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

p {
  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;
}

p {
  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 !important

CSS Math Functions

 

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

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(value1, value2, ...)
Value Description
value1, value2, ... 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(value1, value2, ...)
Value Description
value1, value2, ... 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
  Allows you to perform calculations to determine CSS property values
  Uses the largest value, from a comma-separated list of values, as the property value
  Uses the smallest value, from a comma-separated list of values, as the property value

 
CSS Math Functions

CSS  Rounded Corners


CSS border-radius Property

The CSS border-radius property defines the radius of an element's corners.

Tip: This property allows you to add rounded corners to elements!

Here are three examples:

1. Rounded corners for an element with a specified background color:

Rounded corners!

2. Rounded corners for an element with a border:

Rounded corners!

3. Rounded corners for an element with a background image:

Rounded corners!

Here is the code:

Example

#rcorners1 {
  border-radius: 25px;
  background: #73AD21;
  padding: 20px;
  width: 200px;
  height: 150px;
}

#rcorners2 {
  border-radius: 25px;
  border: 2px solid #73AD21;
  padding: 20px;
  width: 200px;
  height: 150px;
}

#rcorners3 {
  border-radius: 25px;
  background: url(paper.gif);
  background-position: left top;
  background-repeat: repeat;
  padding: 20px;
  width: 200px;
  height: 150px;
}

Tip: The border-radius property is actually a shorthand property for the border-top-left-radius, border-top-right-radius, border-bottom-right-radius and border-bottom-left-radius properties.



CSS border-radius - Specify Each Corner

The border-radius property can have from one to four values. Here are the rules:

Four values - border-radius: 15px 50px 30px 5px; (first value applies to top-left corner, second value applies to top-right corner, third value applies to bottom-right corner, and fourth value applies to bottom-left corner): 

Three values - border-radius: 15px 50px 30px; (first value applies to top-left corner, second value applies to top-right and bottom-left corners, and third value applies to bottom-right corner):

Two values - border-radius: 15px 50px; (first value applies to top-left and bottom-right corners, and the second value applies to top-right and bottom-left corners):

One value - border-radius: 15px; (the value applies to all four corners, which are rounded equally:

Here is the code:

Example

#rcorners1 {
  border-radius: 15px 50px 30px 5px;
  background: #73AD21;
  padding: 20px;
  width: 200px;
  height: 150px;
}

#rcorners2 {
  border-radius: 15px 50px 30px;
  background: #73AD21;
  padding: 20px;
  width: 200px;
  height: 150px;
}

#rcorners3 {
  border-radius: 15px 50px;
  background: #73AD21;
  padding: 20px;
  width: 200px;
  height: 150px;
}

#rcorners4 {
  border-radius: 15px;
  background: #73AD21;
  padding: 20px;
  width: 200px;
  height: 150px;
}

You could also create elliptical corners:

Example

#rcorners1 {
  border-radius: 50px / 15px;
  background: #73AD21;
  padding: 20px;
  width: 200px;
  height: 150px;
}

#rcorners2 {
  border-radius: 15px / 50px;
  background: #73AD21;
  padding: 20px;
  width: 200px;
  height: 150px;
}

#rcorners3 {
  border-radius: 50%;
  background: #73AD21;
  padding: 20px;
  width: 200px;
  height: 150px;
}

Test Yourself With Exercises

Exercise:

Give the div element rounded corners.



  
This is a div element. It has some text.


 


CSS Rounded Corners Properties

Property Description
  A shorthand property for setting all the four border-*-*-radius properties
  Defines the shape of the border of the top-left corner
  Defines the shape of the border of the top-right corner
  Defines the shape of the border of the bottom-right corner
  Defines the shape of the border of the bottom-left corner

 

 
CSS Rounded Corners

CSS Border Images

 

CSS Border Images

With the CSS border-image property, you can set an image to be used as the border around an element.


CSS border-image Property

The CSS border-image property allows you to specify an image to be used instead of the normal border around an element.

The property has three parts:

  1. The image to use as the border
  2. Where to slice the image
  3. Define whether the middle sections should be repeated or stretched

We will use the following image (called "border.png"):

 

The border-image property takes the image and slices it into nine sections, like a tic-tac-toe board. It then places the corners at the corners, and the middle sections are repeated or stretched as you specify.

Note: For border-image to work, the element also needs the border property set!

Here, the middle sections of the image are repeated to create the border:

An image as a border!

Here is the code:

Example

#borderimg {
  border: 10px solid transparent;
  padding: 15px;
  border-image: url(border.png) 30 round;
}

Here, the middle sections of the image are stretched to create the border:

An image as a border!

Here is the code:

Example

#borderimg {
  border: 10px solid transparent;
  padding: 15px;
  border-image: url(border.png) 30 stretch;
}

Tip: The border-image property is actually a shorthand property for the border-image-source, border-image-slice, border-image-width, border-image-outset and border-image-repeat properties.



CSS border-image - Different Slice Values

Example

#borderimg1 {
  border: 10px solid transparent;
  padding: 15px;
  border-image: url(border.png) 50 round;
}

#borderimg2 {
  border: 10px solid transparent;
  padding: 15px;
  border-image: url(border.png) 20% round;
}

#borderimg3 {
  border: 10px solid transparent;
  padding: 15px;
  border-image: url(border.png) 30% round;
}

Test Yourself With Exercises

Exercise:

Give the div element an image border. Use the short hand property to define the details of the image border.



  
This is a div element. It has some text.


 


CSS Border Image Properties

Property Description
  A shorthand property for setting all the border-image-* properties
  Specifies the path to the image to be used as a border
  Specifies how to slice the border image
  Specifies the widths of the border image
  Specifies the amount by which the border image area extends beyond the border box
  Specifies whether the border image should be repeated, rounded or stretched

 

 
CSS Border Images

CSS Multiple Backgrounds

 

In this chapter you will learn how to add multiple background images to one element.

You will also learn about the following properties:

  • background-size
  • background-origin
  • background-clip

CSS Multiple Backgrounds

CSS allows you to add multiple background images for an element, through the background-image property.

The different background images are separated by commas, and the images are stacked on top of each other, where the first image is closest to the viewer.

The following example has two background images, the first image is a flower (aligned to the bottom and right) and the second image is a paper background (aligned to the top-left corner):

Example

#example1 {
  background-image: url(img_flwr.gif), url(paper.gif);
  background-position: right bottom, left top;
  background-repeat: no-repeat, repeat;
}

Multiple background images can be specified using either the individual background properties (as above) or the background shorthand property.

The following example uses the background shorthand property (same result as example above):

Example

#example1 {
  background: url(img_flwr.gif) right bottom no-repeat, url(paper.gif) left top repeat;
}


CSS Background Size

The CSS background-size property allows you to specify the size of background images.

The size can be specified in lengths, percentages, or by using one of the two keywords: contain or cover.

The following example resizes a background image to much smaller than the original image (using pixels):

Lorem Ipsum Dolor

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.

Here is the code:

Example

#div1 {
  background: url(img_flower.jpg);
  background-size: 100px 80px;
  background-repeat: no-repeat;
}

The two other possible values for background-size are contain and cover.

The contain keyword scales the background image to be as large as possible (but both its width and its height must fit inside the content area). As such, depending on the proportions of the background image and the background positioning area, there may be some areas of the background which are not covered by the background image.

The cover keyword scales the background image so that the content area is completely covered by the background image (both its width and height are equal to or exceed the content area). As such, some parts of the background image may not be visible in the background positioning area.

The following example illustrates the use of contain and cover:

Example

#div1 {
  background: url(img_flower.jpg);
  background-size: contain;
  background-repeat: no-repeat;
}

#div2 {
  background: url(img_flower.jpg);
  background-size: cover;
  background-repeat: no-repeat;
}

Define Sizes of Multiple Background Images

The background-size property also accepts multiple values for background size (using a comma-separated list), when working with multiple backgrounds.

The following example has three background images specified, with different background-size value for each image:

Example

#example1 {
  background: url(img_tree.gif) left top no-repeat, url(img_flwr.gif) right bottom no-repeat, url(paper.gif) left top repeat;
  background-size: 50px, 130px, auto;
}

Full Size Background Image

Now we want to have a background image on a website that covers the entire browser window at all times.

The requirements are as follows:

  • Fill the entire page with the image (no white space)
  • Scale image as needed
  • Center image on page
  • Do not cause scrollbars

The following example shows how to do it; Use the element (the element is always at least the height of the browser window). Then set a fixed and centered background on it. Then adjust its size with the background-size property:

Example

html {
  background: url(img_man.jpg) no-repeat center fixed;
  background-size: cover;
}

Hero Image

You could also use different background properties on a

to create a hero image (a large image with text), and place it where you want.

 

Example

.hero-image {
  background: url(img_man.jpg) no-repeat center;
  background-size: cover;
  height: 500px;
  position: relative;
}

CSS background-origin Property

The CSS background-origin property specifies where the background image is positioned.

The property takes three different values:

  • border-box - the background image starts from the upper left corner of the border
  • padding-box - (default) the background image starts from the upper left corner of the padding edge
  • content-box - the background image starts from the upper left corner of the content

The following example illustrates the background-origin property:

Example

#example1 {
  border: 10px solid black;
  padding: 35px;
  background: url(img_flwr.gif);
  background-repeat: no-repeat;
  background-origin: content-box;
}

CSS background-clip Property

The CSS background-clip property specifies the painting area of the background.

The property takes three different values:

  • border-box - (default) the background is painted to the outside edge of the border
  • padding-box - the background is painted to the outside edge of the padding
  • content-box - the background is painted within the content box

The following example illustrates the background-clip property:

Example

#example1 {
  border: 10px dotted black;
  padding: 35px;
  background: yellow;
  background-clip: content-box;
}

Test Yourself With Exercises

Exercise:

Add two background images to the element.

img1.gif and img2.gif.

Make sure that img2.gif is displayed on top of img1.gif.

 

 


CSS Advanced Background Properties

Property Description
  A shorthand property for setting all the background properties in one declaration
  Specifies the painting area of the background
  Specifies one or more background images for an element
  Specifies where the background image(s) is/are positioned
  Specifies the size of the background image(s)

 
CSS Backgrounds

CSS Colors

 

CSS supports , RGBA values, HSL values, HSLA values, and opacity.


RGBA Colors

RGBA color values are an extension of RGB color values with an alpha channel - which specifies the opacity for a color.

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).

rgba(255, 0, 0, 0.2);
rgba(255, 0, 0, 0.4);
rgba(255, 0, 0, 0.6);
rgba(255, 0, 0, 0.8);

The following example defines different RGBA colors:

Example

#p1 {background-color: rgba(255, 0, 0, 0.3);}  /* red with opacity */
#p2 {background-color: rgba(0, 255, 0, 0.3);}  /* green with opacity */
#p3 {background-color: rgba(0, 0, 255, 0.3);}  /* blue with opacity */


HSL Colors

HSL stands for Hue, Saturation and Lightness.

An HSL color value is specified with: hsl(hue, saturation, lightness).

  1. Hue is a degree on the color wheel (from 0 to 360):
    • 0 (or 360) is red
    • 120 is green
    • 240 is blue
  2. Saturation is a percentage value: 100% is the full color.
  3. Lightness is also a percentage; 0% is dark (black) and 100% is white.
hsl(0, 100%, 30%);
hsl(0, 100%, 50%);
hsl(0, 100%, 70%);
hsl(0, 100%, 90%);

The following example defines different HSL colors:

Example

#p1 {background-color: hsl(120, 100%, 50%);}  /* green */
#p2 {background-color: hsl(120, 100%, 75%);}  /* light green */
#p3 {background-color: hsl(120, 100%, 25%);}  /* dark green */
#p4 {background-color: hsl(120, 60%, 70%);}   /* pastel green */

HSLA Colors

HSLA color values are an extension of HSL color values with an alpha channel - which specifies the opacity for a color.

An HSLA color value is specified with: hsla(hue, saturation, lightness, alpha), where the alpha parameter defines the opacity. The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).

hsla(0, 100%, 30%, 0.3);
hsla(0, 100%, 50%, 0.3);
hsla(0, 100%, 70%, 0.3);
hsla(0, 100%, 90%, 0.3);

The following example defines different HSLA colors:

Example

#p1 {background-color: hsla(120, 100%, 50%, 0.3);}  /* green with opacity */
#p2 {background-color: hsla(120, 100%, 75%, 0.3);}  /* light green with opacity */
#p3 {background-color: hsla(120, 100%, 25%, 0.3);}  /* dark green with opacity */
#p4 {background-color: hsla(120, 60%, 70%, 0.3);}   /* pastel green with opacity */

Opacity

The CSS opacity property sets the opacity for the whole element (both background color and text will be opaque/transparent).

The opacity property value must be a number between 0.0 (fully transparent) and 1.0 (fully opaque).

rgb(255, 0, 0);opacity:0.2;
rgb(255, 0, 0);opacity:0.4;
rgb(255, 0, 0);opacity:0.6;
rgb(255, 0, 0);opacity:0.8;

Notice that the text above will also be transparent/opaque!

The following example shows different elements with opacity:

Example

#p1 {background-color:rgb(255,0,0);opacity:0.6;}  /* red with opacity */
#p2 {background-color:rgb(0,255,0);opacity:0.6;}  /* green with opacity */
#p3 {background-color:rgb(0,0,255);opacity:0.6;}  /* blue with opacity */

Test Yourself With Exercises

Exercise:

Insert the RGBA color value for a full red background color of the

element, with no transparency.

 
CSS Colors

CSS Color Keywords

 

This page will explain the transparent, currentcolor, and inherit keywords.


The transparent Keyword

The transparent keyword is used to make a color transparent. This is often used to make a transparent background color for an element.

Example

Here, the background color of the

element will be fully transparent, and the background image will show through:

 

body {
  background-image: url("paper.gif");
}

div {
  background-color: transparent;
}

Note: The transparent keyword is equivalent to rgba(0,0,0,0). RGBA color values are an extension of RGB color values with an alpha channel - which specifies the opacity for a color. Read more in our chapter and in our chapter.


The currentcolor Keyword

The currentcolor keyword is like a variable that holds the current value of the color property of an element.

This keyword can be useful if you want a specific color to be consistent in an element or a page.

Example

In this example the border color of the

element will be blue, because the text color of the
element is blue:

 

div {
  color: blue;
  border: 10px solid currentcolor;
}

Example

In this example the

's background color is set to the current color value of the body element:

 

body {
  color: purple;
}

div {
  background-color: currentcolor;
}

Example

In this example the

's border color and shadow color is set to the current color value of the body element:

 

body {
 color: green;
}

div {
  box-shadow: 0px 0px 15px currentcolor;
  border: 5px solid currentcolor;
}

The inherit Keyword

The inherit keyword specifies that a property should inherit its value from its parent element.

The inherit keyword can be used for any CSS property, and on any HTML element.

Example

In this example the 's border settings will be inherited from the parent element: 

div {
  border: 2px solid red;
}

span {
  border: inherit;
}

 
CSS Color Keywords

CSS Gradients

Gradient Backgrounds


CSS gradients let you display smooth transitions between two or more specified colors.

CSS defines three types of gradients:

  • Linear Gradients (goes down/up/left/right/diagonally)
  • Radial Gradients (defined by their center)
  • Conic Gradients (rotated around a center point)

CSS Linear Gradients

To create a linear gradient you must define at least two color stops. Color stops are the colors you want to render smooth transitions among. You can also set a starting point and a direction (or an angle) along with the gradient effect.

Syntax

background-image: linear-gradient(direction, color-stop1, color-stop2, ...);

Direction - Top to Bottom (this is default)

The following example shows a linear gradient that starts at the top. It starts red, transitioning to yellow:

top to bottom (default)

Example

#grad {
  background-image: linear-gradient(red, yellow);
}

Direction - Left to Right

The following example shows a linear gradient that starts from the left. It starts red, transitioning to yellow:

left to right

Example

#grad {
  background-image: linear-gradient(to right, red , yellow);
}

Direction - Diagonal

You can make a gradient diagonally by specifying both the horizontal and vertical starting positions.

The following example shows a linear gradient that starts at top left (and goes to bottom right). It starts red, transitioning to yellow:

top left to bottom right

Example

#grad {
  background-image: linear-gradient(to bottom right, red, yellow);
}


Using Angles

If you want more control over the direction of the gradient, you can define an angle, instead of the predefined directions (to bottom, to top, to right, to left, to bottom right, etc.). A value of 0deg is equivalent to "to top". A value of 90deg is equivalent to "to right". A value of 180deg is equivalent to "to bottom".

Syntax

background-image: linear-gradient(angle, color-stop1, color-stop2);

The following example shows how to use angles on linear gradients:

180deg

Example

#grad {
  background-image: linear-gradient(180deg, red, yellow);
}

Using Multiple Color Stops

The following example shows a linear gradient (from top to bottom) with multiple color stops:

Example

#grad {
  background-image: linear-gradient(red, yellow, green);
}

The following example shows how to create a linear gradient (from left to right) with the color of the rainbow and some text:

Rainbow Background

Example

#grad {
  background-image: linear-gradient(to right, red,orange,yellow,green,blue,indigo,violet);
}

Using Transparency

CSS gradients also support transparency, which can be used to create fading effects.

To add transparency, we use the rgba() function to define the color stops. The last parameter in the rgba() function can be a value from 0 to 1, and it defines the transparency of the color: 0 indicates full transparency, 1 indicates full color (no transparency).

The following example shows a linear gradient that starts from the left. It starts fully transparent, transitioning to full color red:

Example

#grad {
  background-image: linear-gradient(to right, rgba(255,0,0,0), rgba(255,0,0,1));
}

Repeating a linear-gradient

The repeating-linear-gradient() function is used to repeat linear gradients:

Example

A repeating linear gradient:

#grad {
  background-image: repeating-linear-gradient(red, yellow 10%, green 20%);
}

 

 
CSS Gradients

CSS Gradients

Gradient Backgrounds


CSS gradients let you display smooth transitions between two or more specified colors.

CSS defines three types of gradients:

  • Linear Gradients (goes down/up/left/right/diagonally)
  • Radial Gradients (defined by their center)
  • Conic Gradients (rotated around a center point)

CSS Linear Gradients

To create a linear gradient you must define at least two color stops. Color stops are the colors you want to render smooth transitions among. You can also set a starting point and a direction (or an angle) along with the gradient effect.

Syntax

background-image: linear-gradient(direction, color-stop1, color-stop2, ...);

Direction - Top to Bottom (this is default)

The following example shows a linear gradient that starts at the top. It starts red, transitioning to yellow:

top to bottom (default)

Example

#grad {
  background-image: linear-gradient(red, yellow);
}

Direction - Left to Right

The following example shows a linear gradient that starts from the left. It starts red, transitioning to yellow:

left to right

Example

#grad {
  background-image: linear-gradient(to right, red , yellow);
}

Direction - Diagonal

You can make a gradient diagonally by specifying both the horizontal and vertical starting positions.

The following example shows a linear gradient that starts at top left (and goes to bottom right). It starts red, transitioning to yellow:

top left to bottom right

Example

#grad {
  background-image: linear-gradient(to bottom right, red, yellow);
}


Using Angles

If you want more control over the direction of the gradient, you can define an angle, instead of the predefined directions (to bottom, to top, to right, to left, to bottom right, etc.). A value of 0deg is equivalent to "to top". A value of 90deg is equivalent to "to right". A value of 180deg is equivalent to "to bottom".

Syntax

background-image: linear-gradient(angle, color-stop1, color-stop2);

The following example shows how to use angles on linear gradients:

180deg

Example

#grad {
  background-image: linear-gradient(180deg, red, yellow);
}

Using Multiple Color Stops

The following example shows a linear gradient (from top to bottom) with multiple color stops:

Example

#grad {
  background-image: linear-gradient(red, yellow, green);
}

The following example shows how to create a linear gradient (from left to right) with the color of the rainbow and some text:

Rainbow Background

Example

#grad {
  background-image: linear-gradient(to right, red,orange,yellow,green,blue,indigo,violet);
}

Using Transparency

CSS gradients also support transparency, which can be used to create fading effects.

To add transparency, we use the rgba() function to define the color stops. The last parameter in the rgba() function can be a value from 0 to 1, and it defines the transparency of the color: 0 indicates full transparency, 1 indicates full color (no transparency).

The following example shows a linear gradient that starts from the left. It starts fully transparent, transitioning to full color red:

Example

#grad {
  background-image: linear-gradient(to right, rgba(255,0,0,0), rgba(255,0,0,1));
}

Repeating a linear-gradient

The repeating-linear-gradient() function is used to repeat linear gradients:

Example

A repeating linear gradient:

#grad {
  background-image: repeating-linear-gradient(red, yellow 10%, green 20%);
}

 

 
Linear Gradients

CSS Radial Gradients

 

CSS Radial Gradients

A radial gradient is defined by its center.

To create a radial gradient you must also define at least two color stops.

Syntax

background-image: radial-gradient(shape size at position, start-color, ..., last-color);

By default, shape is ellipse, size is farthest-corner, and position is center.

Radial Gradient - Evenly Spaced Color Stops (this is default)

The following example shows a radial gradient with evenly spaced color stops:

Example

#grad {
  background-image: radial-gradient(red, yellow, green);
}

Radial Gradient - Differently Spaced Color Stops

The following example shows a radial gradient with differently spaced color stops:

Example

#grad {
  background-image: radial-gradient(red 5%, yellow 15%, green 60%);
}

Set Shape

The shape parameter defines the shape. It can take the value circle or ellipse. The default value is ellipse.

The following example shows a radial gradient with the shape of a circle:

Example

#grad {
  background-image: radial-gradient(circle, red, yellow, green);
}


Use of Different Size Keywords

The size parameter defines the size of the gradient. It can take four values:

  • closest-side
  • farthest-side
  • closest-corner
  • farthest-corner

Example

A radial gradient with different size keywords:

#grad1 {
  background-image: radial-gradient(closest-side at 60% 55%, red, yellow, black);
}

#grad2 {
  background-image: radial-gradient(farthest-side at 60% 55%, red, yellow, black);
}

Repeating a radial-gradient

The repeating-radial-gradient() function is used to repeat radial gradients:

Example

A repeating radial gradient:

#grad {
  background-image: repeating-radial-gradient(red, yellow 10%, green 15%);
}

Test Yourself With Exercises

Exercise:

Set a linear gradient background for the

element, going from the top to bottom, transitioning from "white" to "green".

 


Radial Gradients

CSS Conic Gradients

 

CSS Conic Gradients

A conic gradient is a gradient with color transitions rotated around a center point.

To create a conic gradient you must define at least two colors.

Syntax

background-image: conic-gradient([from angle] [at position,] color [degree], color [degree], ...);

By default, angle is 0deg and position is center.

If no degree is specified, the colors will be spread equally around the center point.


Conic Gradient: Three Colors

The following example shows a conic gradient with three colors:

Example

A conic gradient with three colors:

#grad {
  background-image: conic-gradient(red, yellow, green);
}

Conic Gradient: Five Colors

The following example shows a conic gradient with five colors:

Example

A conic gradient with five colors:

#grad {
  background-image: conic-gradient(red, yellow, green, blue, black);
}

Conic Gradient: Three Colors and Degrees

The following example shows a conic gradient with three colors and a degree for each color:

Example

A conic gradient with three colors and a degree for each color:

#grad {
  background-image: conic-gradient(red 45deg, yellow 90deg, green 210deg);
}


Create Pie Charts

Just add border-radius: 50% to make the conic gradient look like a pie:

Example

#grad {
  background-image: conic-gradient(red, yellow, green, blue, black);
  border-radius: 50%;
}

Here is another pie chart with defined degrees for all the colors:

Example

#grad {
  background-image: conic-gradient(red 0deg, red 90deg, yellow 90deg, yellow 180deg, green 180deg, green 270deg, blue 270deg);
  border-radius: 50%;
}

Conic Gradient With Specified From Angle

The [from angle] specifies an angle that the entire conic gradient is rotated by.

The following example shows a conic gradient with a from angle of 90deg:

Example

A conic gradient with a from angle:

#grad {
  background-image: conic-gradient(from 90deg, red, yellow, green);
}

Conic Gradient With Specified Center Position

The [at position] specifies the center of the conic gradient.

The following example shows a conic gradient with a center position of 60% 45%:

Example

A conic gradient with a specified center position:

#grad {
  background-image: conic-gradient(at 60% 45%, red, yellow, green);
}

Repeating a Conic Gradient

The repeating-conic-gradient() function is used to repeat conic gradients:

Example

A repeating conic gradient:

#grad {
  background-image: repeating-conic-gradient(red 10%, yellow 20%);
  border-radius: 50%;
}

Here is a repeating conic gradient with defined color-starts and color-stops:

Example

A repeating conic gradient with defined color-starts and color-stops:

#grad {
  background-image: repeating-conic-gradient(red 0deg 10deg, yellow 10deg 20deg, blue 20deg 30deg);
  border-radius: 50%;
}

CSS Gradient Functions

The following table lists the CSS gradient functions:

Function Description
  Creates a conic gradient. Define at least two colors (around a center point)
  Creates a linear gradient. Define at least two colors (top to bottom)
  Creates a radial gradient. Define at least two colors (center to edges)
  Repeats a conic gradient
  Repeats a linear gradient
  Repeats a radial gradient

 

 
Conic Gradients

CSS Shadow Effects

 

With CSS you can create shadow effects!

Hover over me!

CSS Shadow Effects

With CSS you can add shadow to text and to elements.

In these chapters you will learn about the following properties:

  • text-shadow
  • box-shadow

CSS Text Shadow

The CSS text-shadow property applies shadow to text.

In its simplest use, you only specify the horizontal shadow (2px) and the vertical shadow (2px):

Text shadow effect!

Example

h1 {
  text-shadow: 2px 2px;
}

Next, add a color to the shadow:

Text shadow effect!

Example

h1 {
  text-shadow: 2px 2px red;
}

Then, add a blur effect to the shadow:

Text shadow effect!

Example

h1 {
  text-shadow: 2px 2px 5px red;
}

The following example shows a white text with black shadow:

Text shadow effect!

Example

h1 {
  color: white;
  text-shadow: 2px 2px 4px #000000;
}

The following example shows a red neon glow shadow:

Text shadow effect!

Example

h1 {
  text-shadow: 0 0 3px #FF0000;
}


Multiple Shadows

To add more than one shadow to the text, you can add a comma-separated list of shadows.

The following example shows a red and blue neon glow shadow:

Text shadow effect!

Example

h1 {
  text-shadow: 0 0 3px #FF0000, 0 0 5px #0000FF;
}

The following example shows a white text with black, blue, and darkblue shadow:

Text shadow effect!

Example

h1 {
  color: white;
  text-shadow: 1px 1px 2px black, 0 0 25px blue, 0 0 5px darkblue;
}

You can also use the text-shadow property to create a plain border around some text (without shadows):

Border around text!

Example

h1 {
  color: coral;
  text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}

 

 
CSS Shadows

CSS Shadow Effects

 

 

With CSS you can create shadow effects!

Hover over me!

CSS Shadow Effects

With CSS you can add shadow to text and to elements.

In these chapters you will learn about the following properties:

  • text-shadow
  • box-shadow

CSS Text Shadow

The CSS text-shadow property applies shadow to text.

In its simplest use, you only specify the horizontal shadow (2px) and the vertical shadow (2px):

Text shadow effect!

Example

h1 {
  text-shadow: 2px 2px;
}

Next, add a color to the shadow:

Text shadow effect!

Example

h1 {
  text-shadow: 2px 2px red;
}

Then, add a blur effect to the shadow:

Text shadow effect!

Example

h1 {
  text-shadow: 2px 2px 5px red;
}

The following example shows a white text with black shadow:

Text shadow effect!

Example

h1 {
  color: white;
  text-shadow: 2px 2px 4px #000000;
}

The following example shows a red neon glow shadow:

Text shadow effect!

Example

h1 {
  text-shadow: 0 0 3px #FF0000;
}


Multiple Shadows

To add more than one shadow to the text, you can add a comma-separated list of shadows.

The following example shows a red and blue neon glow shadow:

Text shadow effect!

Example

h1 {
  text-shadow: 0 0 3px #FF0000, 0 0 5px #0000FF;
}

The following example shows a white text with black, blue, and darkblue shadow:

Text shadow effect!

Example

h1 {
  color: white;
  text-shadow: 1px 1px 2px black, 0 0 25px blue, 0 0 5px darkblue;
}

You can also use the text-shadow property to create a plain border around some text (without shadows):

Border around text!

Example

h1 {
  color: coral;
  text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}

 

 
Shadow Effects

CSS Box Shadow

 

CSS box-shadow Property

The CSS box-shadow property is used to apply one or more shadows to an element.


Specify a Horizontal and a Vertical Shadow

In its simplest use, you only specify a horizontal and a vertical shadow. The default color of the shadow is the current text-color.

A
element with a box-shadow

Example

Specify a horizontal and a vertical shadow:

div {
  box-shadow: 10px 10px;
}

Specify a Color for the Shadow

The color parameter defines the color of the shadow.

A
element with a lightblue box-shadow

Example

Specify a color for the shadow:

div {
  box-shadow: 10px 10px lightblue;
}

Add a Blur Effect to the Shadow

The blur parameter defines the blur radius. The higher the number, the more blurred the shadow will be.

A
element with a 5px blurred, lightblue box-shadow

Example

Add a blur effect to the shadow:

div {
  box-shadow: 10px 10px 5px lightblue;
}

Set the Spread Radius of the Shadow

The spread parameter defines the spread radius. A positive value increases the size of the shadow, a negative value decreases the size of the shadow.

A
element with a blurred, lightblue box-shadow, with a spread radius of 12px

Example

Set the spread radius of the shadow:

div {
  box-shadow: 10px 10px 5px 12px lightblue;
}


Set the inset Parameter

The inset parameter changes the shadow from an outer shadow (outset) to an inner shadow.

A
element with a blurred, lightblue, inset box-shadow

Example

Add the inset parameter:

div {
  box-shadow: 10px 10px 5px lightblue inset;
}

Add Multiple Shadows

An element can also have multiple shadows:

Example

div {
  box-shadow: 5px 5px blue, 10px 10px red, 15px 15px green;
}

Cards

You can also use the box-shadow property to create paper-like cards:

Hardanger, Norway

Example

div.card {
  width: 250px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  text-align: center;
}

Test Yourself With Exercises

Exercise:

Set a "2px" horizontal, and "2px" vertical, text shadow for the

element.


CSS Shadow Properties

The following table lists the CSS shadow properties:

Property Description
  Adds one or more shadows to an element
  Adds one or more shadows to a text

 
Box Shadow

CSS Text Effects

 

CSS Text Overflow, Word Wrap, Line Breaking Rules, and Writing Modes

In this chapter you will learn about the following properties:

  • text-overflow
  • word-wrap
  • word-break
  • writing-mode

CSS Text Overflow

The CSS text-overflow property specifies how overflowed content that is not displayed should be signaled to the user.

It can be clipped:

This is some long text that will not fit in the box

or it can be rendered as an ellipsis (...):

This is some long text that will not fit in the box

The CSS code is as follows:

Example

p.test1 {
  white-space: nowrap;
  width: 200px;
  border: 1px solid #000000;
  overflow: hidden;
  text-overflow: clip;
}

p.test2 {
  white-space: nowrap;
  width: 200px;
  border: 1px solid #000000;
  overflow: hidden;
  text-overflow: ellipsis;
}

The following example shows how you can display the overflowed content when hovering over the element:

Example

div.test:hover {
  overflow: visible;
}


CSS Word Wrapping

The CSS word-wrap property allows long words to be able to be broken and wrap onto the next line. 

If a word is too long to fit within an area, it expands outside:

This paragraph contains a very long word: thisisaveryveryveryveryveryverylongword. The long word will break and wrap to the next line.

The word-wrap property allows you to force the text to wrap - even if it means splitting it in the middle of a word:

This paragraph contains a very long word: thisisaveryveryveryveryveryverylongword. The long word will break and wrap to the next line.

The CSS code is as follows:

Example

Allow long words to be able to be broken and wrap onto the next line:

p {
  word-wrap: break-word;
}

CSS Word Breaking

The CSS word-break property specifies line breaking rules.

This paragraph contains some text. This line will-break-at-hyphens.

This paragraph contains some text. The lines will break at any character.

The CSS code is as follows:

Example

p.test1 {
  word-break: keep-all;
}

p.test2 {
  word-break: break-all;
}

CSS Writing Mode

The CSS writing-mode property specifies whether lines of text are laid out horizontally or vertically.

Some text with a span element with a vertical-rl writing-mode.

The following example shows some different writing modes:

Example

p.test1 {
  writing-mode: horizontal-tb;
}

span.test2 {
  writing-mode: vertical-rl;
}

p.test2 {
  writing-mode: vertical-rl;
}

Test Yourself With Exercises

Exercise:

Specify that the overflowed content for the

element should be signaled with an ellipsis (...).



  

This paragraph contains a very long word: supercalifragilisticexpialidocious.



 


CSS Text Effect Properties

The following table lists the CSS text effect properties:

Property Description
  Specifies how justified text should be aligned and spaced
  Specifies how overflowed content that is not displayed should be signaled to the user
  Specifies line breaking rules for non-CJK scripts
  Allows long words to be able to be broken and wrap onto the next line
  Specifies whether lines of text are laid out horizontally or vertically

 

 
CSS Text Effects

CSS Web Fonts

 

The CSS @font-face Rule

Web fonts allow Web designers to use fonts that are not installed on the user's computer.

When you have found/bought the font you wish to use, just include the font file on your web server, and it will be automatically downloaded to the user when needed.

Your "own" fonts are defined within the CSS @font-face rule.


Different Font Formats

TrueType Fonts (TTF)

TrueType is a font standard developed in the late 1980s, by Apple and Microsoft. TrueType is the most common font format for both the Mac OS and Microsoft Windows operating systems.

OpenType Fonts (OTF)

OpenType is a format for scalable computer fonts. It was built on TrueType, and is a registered trademark of Microsoft. OpenType fonts are used commonly today on the major computer platforms.

The Web Open Font Format (WOFF)

WOFF is a font format for use in web pages. It was developed in 2009, and is now a W3C Recommendation. WOFF is essentially OpenType or TrueType with compression and additional metadata. The goal is to support font distribution from a server to a client over a network with bandwidth constraints.

The Web Open Font Format (WOFF 2.0)

TrueType/OpenType font that provides better compression than WOFF 1.0.

SVG Fonts/Shapes

SVG fonts allow SVG to be used as glyphs when displaying text. The SVG 1.1 specification define a font module that allows the creation of fonts within an SVG document. You can also apply CSS to SVG documents, and the @font-face rule can be applied to text in SVG documents.

Embedded OpenType Fonts (EOT)

EOT fonts are a compact form of OpenType fonts designed by Microsoft for use as embedded fonts on web pages.



Browser Support for Font Formats

The numbers in the table specifies the first browser version that fully supports the font format.

Font format          
TTF/OTF 9.0* 4.0 3.5 3.1 10.0
WOFF 9.0 5.0 3.6 5.1 11.1
WOFF2 14.0 36.0 39.0 10.0 26.0
SVG Not supported Not supported Not supported 3.2 Not supported
EOT 6.0 Not supported Not supported Not supported Not supported

*IE: The font format only works when set to be "installable".


Using The Font You Want

In the @font-face rule; first define a name for the font (e.g. myFirstFont) and then point to the font file.

Tip: Always use lowercase letters for the font URL. Uppercase letters can give unexpected results in IE.

To use the font for an HTML element, refer to the name of the font (myFirstFont) through the font-family property:

Example

@font-face {
  font-family: myFirstFont;
  src: url(sansation_light.woff);
}

div {
  font-family: myFirstFont;
}

Using Bold Text

You must add another @font-face rule containing descriptors for bold text:

Example

@font-face {
  font-family: myFirstFont;
  src: url(sansation_bold.woff);
  font-weight: bold;
}

The file "sansation_bold.woff" is another font file, that contains the bold characters for the Sansation font.

Browsers will use this whenever a piece of text with the font-family "myFirstFont" should render as bold.

This way you can have many @font-face rules for the same font.


Test Yourself With Exercises

Exercise:

Add a web font with the name "sansation" and the URL "sansation_light.woff".

 

 


CSS Font Descriptors

The following table lists all the font descriptors that can be defined inside the @font-face rule:

Descriptor Values Description
font-family name Required. Defines a name for the font
src URL Required. Defines the URL of the font file
font-stretch normal
condensed
ultra-condensed
extra-condensed
semi-condensed
expanded
semi-expanded
extra-expanded
ultra-expanded
Optional. Defines how the font should be stretched. Default is "normal"
font-style normal
italic
oblique
Optional. Defines how the font should be styled. Default is "normal"
font-weight normal
bold
100
200
300
400
500
600
700
800
900
Optional. Defines the boldness of the font. Default is "normal"
unicode-range unicode-range Optional. Defines the range of UNICODE characters the font supports. Default is "U+0-10FFFF"

 

 
CSS Web Fonts

CSS transforms allow you to move, rotate, scale, and skew elements.

kkk kkll
transform 10.0 16.0

TranslateC

CSS

 

Mouse over the elemet low to see a 2D transformation:

 

2D rotate
       
         
         

In this chapter you will learn about the following CSS property:

  • transform

Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Property          
transform 36.0 10.0 16.0 9.0 23.0

CSS 2D Transforms Methods

With the CSS transform property you can use the following 2D transformation methods:

  • translate()
  • rotate()
  • scaleX()
  • scaleY()
  • scale()
  • skewX()
  • skewY()
  • skew()
  • matrix()

Tip: You will learn about 3D transformations in the next chapter.


The translate() Method

the translate() method moves an element from its current position (according to the parameters given for the X-axis and the Y-axis).

The following example moves the

element 50 pixels to the right, and 100 pixels down from its current position:

 

Example

div {
  transform: translate(50px, 100px);
}

The rotate() Method

Rotate

The rotate() method rotates an element clockwise or counter-clockwise according to a given degree.

The following example rotates the

element clockwise with 20 degrees:

 

Example

div {
  transform: rotate(20deg);
}

Using negative values will rotate the element counter-clockwise.

The following example rotates the

element counter-clockwise with 20 degrees:

 

Example

div {
  transform: rotate(-20deg);
}


The scale() Method

The scale() method increases or decreases the size of an element (according to the parameters given for the width and height).

 

The following example increases the

element to be two times of its original width, and three times of its original height: 

 

Example

div {
  transform: scale(2, 3);
}

The following example decreases the

element to be half of its original width and height: 

 

Example

div {
  transform: scale(0.5, 0.5);
}

The scaleX() Method

The scaleX() method increases or decreases the width of an element.

The following example increases the

element to be two times of its original width: 

 

Example

div {
  transform: scaleX(2);
}

The following example decreases the

element to be half of its original width: 

 

Example

div {
  transform: scaleX(0.5);
}

The scaleY() Method

The scaleY() method increases or decreases the height of an element.

The following example increases the

element to be three times of its original height: 

 

Example

div {
  transform: scaleY(3);
}

The following example decreases the

element to be half of its original height: 

 

Example

div {
  transform: scaleY(0.5);
}

The skewX() Method

The skewX() method skews an element along the X-axis by the given angle.

The following example skews the

element 20 degrees along the X-axis:

 

Example

div {
  transform: skewX(20deg);
}

The skewY() Method

The skewY() method skews an element along the Y-axis by the given angle.

The following example skews the

element 20 degrees along the Y-axis:

 

Example

div {
  transform: skewY(20deg);
}

The skew() Method

The skew() method skews an element along the X and Y-axis by the given angles.

The following example skews the

element 20 degrees along the X-axis, and 10 degrees along the Y-axis:

 

Example

div {
  transform: skew(20deg, 10deg);
}

If the second parameter is not specified, it has a zero value. So, the following example skews the

element 20 degrees along the X-axis:

 

Example

div {
  transform: skew(20deg);
}

The matrix() Method

Rotate

The matrix() method combines all the 2D transform methods into one.

The matrix() method take six parameters, containing mathematic functions, which allows you to rotate, scale, move (translate), and skew elements.

The parameters are as follow: matrix(scaleX(), skewY(), skewX(), scaleY(), translateX(), translateY())

Example

div {
  transform: matrix(1, -0.3, 0, 1, 0, 0);
}

Test Yourself With Exercises

Exercise:

With the transform property, move the

element 100px to the right, and 200px down.
  
This is a div
 

 


CSS Transform Properties

The following table lists all the 2D transform properties:

Property Description
  Applies a 2D or 3D transformation to an element
  Allows you to change the position on transformed elements

CSS 2D Transform Methods

Function Description
matrix(n,n,n,n,n,n) Defines a 2D transformation, using a matrix of six values
translate(x,y) Defines a 2D translation, moving the element along the X- and the Y-axis
translateX(n) Defines a 2D translation, moving the element along the X-axis
translateY(n) Defines a 2D translation, moving the element along the Y-axis
scale(x,y) Defines a 2D scale transformation, changing the elements width and height
scaleX(n) Defines a 2D scale transformation, changing the element's width
scaleY(n) Defines a 2D scale transformation, changing the element's height
rotate(angle) Defines a 2D rotation, the angle is specified in the parameter
skew(x-angle,y-angle) Defines a 2D skew transformation along the X- and the Y-axis
skewX(angle) Defines a 2D skew transformation along the X-axis
skewY(angle) Defines a 2D skew transformation along the Y-axis

 
CSS 2D Transforms
 

CSS 3D Transforms

CSS also supports 3D transformations.

Mouse over the elements below to see the difference between a 2D and a 3D transformation:

2D rotate
3D rotate

In this chapter you will learn about the following CSS property:

  • transform

Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Property          
transform 36.0 10.0 16.0 9.0 23.0

CSS 3D Transforms Methods

With the CSS transform property you can use the following 3D transformation methods:

  • rotateX()
  • rotateY()
  • rotateZ()

The rotateX() Method

The rotateX() method rotates an element around its X-axis at a given degree:

Example

#myDiv {
  transform: rotateX(150deg);
}

The rotateY() Method

The rotateY() method rotates an element around its Y-axis at a given degree:

Example

#myDiv {
  transform: rotateY(150deg);
}

The rotateZ() Method

The rotateZ() method rotates an element around its Z-axis at a given degree:

Example

#myDiv {
  transform: rotateZ(90deg);
}


Test Yourself With Exercises

Exercise:

With the transform property, rotate the

element 150deg around its X-axis..

 

  
This is a div
 

 


CSS Transform Properties

The following table lists all the 3D transform properties:

Property Description
  Applies a 2D or 3D transformation to an element
  Allows you to change the position on transformed elements
  Specifies how nested elements are rendered in 3D space
  Specifies the perspective on how 3D elements are viewed
  Specifies the bottom position of 3D elements
  Defines whether or not an element should be visible when not facing the screen

CSS 3D Transform Methods

Function Description
matrix3d
(n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n)
Defines a 3D transformation, using a 4x4 matrix of 16 values
translate3d(x,y,z) Defines a 3D translation
translateX(x) Defines a 3D translation, using only the value for the X-axis
translateY(y) Defines a 3D translation, using only the value for the Y-axis
translateZ(z) Defines a 3D translation, using only the value for the Z-axis
scale3d(x,y,z) Defines a 3D scale transformation
scaleX(x) Defines a 3D scale transformation by giving a value for the X-axis
scaleY(y) Defines a 3D scale transformation by giving a value for the Y-axis
scaleZ(z) Defines a 3D scale transformation by giving a value for the Z-axis
rotate3d(x,y,z,angle) Defines a 3D rotation
rotateX(angle) Defines a 3D rotation along the X-axis
rotateY(angle) Defines a 3D rotation along the Y-axis
rotateZ(angle) Defines a 3D rotation along the Z-axis
perspective(n) Defines a perspective view for a 3D transformed element

 
CSS 3D Transforms
 

CSS Transitions

CSS transitions allows you to change property values smoothly, over a given duration.

Mouse over the element below to see a CSS transition effect:

CSS

In this chapter you will learn about the following properties:

  • transition
  • transition-delay
  • transition-duration
  • transition-property
  • transition-timing-function

Browser Support for Transitions

The numbers in the table specify the first browser version that fully supports the property.

Property          
transition 26.0 10.0 16.0 6.1 12.1
transition-delay 26.0 10.0 16.0 6.1 12.1
transition-duration 26.0 10.0 16.0 6.1 12.1
transition-property 26.0 10.0 16.0 6.1 12.1
transition-timing-function 26.0 10.0 16.0 6.1 12.1

How to Use CSS Transitions?

To create a transition effect, you must specify two things:

  • the CSS property you want to add an effect to
  • the duration of the effect

Note: If the duration part is not specified, the transition will have no effect, because the default value is 0.

The following example shows a 100px * 100px red

element. The
element has also specified a transition effect for the width property, with a duration of 2 seconds:

 

Example

div {
  width: 100px;
  height: 100px;
  background: red;
  transition: width 2s;
}

The transition effect will start when the specified CSS property (width) changes value.

Now, let us specify a new value for the width property when a user mouses over the

element:

 

Example

div:hover {
  width: 300px;
}

Notice that when the cursor mouses out of the element, it will gradually change back to its original style.


Change Several Property Values

The following example adds a transition effect for both the width and height property, with a duration of 2 seconds for the width and 4 seconds for the height:

Example

div {
  transition: width 2s, height 4s;
}


Specify the Speed Curve of the Transition

The transition-timing-function property specifies the speed curve of the transition effect.

The transition-timing-function property can have the following values:

  • ease - specifies a transition effect with a slow start, then fast, then end slowly (this is default)
  • linear - specifies a transition effect with the same speed from start to end
  • ease-in - specifies a transition effect with a slow start
  • ease-out - specifies a transition effect with a slow end
  • ease-in-out - specifies a transition effect with a slow start and end
  • cubic-bezier(n,n,n,n) - lets you define your own values in a cubic-bezier function

The following example shows some of the different speed curves that can be used:

Example

#div1 {transition-timing-function: linear;}
#div2 {transition-timing-function: ease;}
#div3 {transition-timing-function: ease-in;}
#div4 {transition-timing-function: ease-out;}
#div5 {transition-timing-function: ease-in-out;}

Delay the Transition Effect

The transition-delay property specifies a delay (in seconds) for the transition effect.

The following example has a 1 second delay before starting:

Example

div {
  transition-delay: 1s;
}

Transition + Transformation

The following example adds a transition effect to the transformation:

Example

div {
  transition: width 2s, height 2s, transform 2s;
}

More Transition Examples

The CSS transition properties can be specified one by one, like this:

Example

div {
  transition-property: width;
  transition-duration: 2s;
  transition-timing-function: linear;
  transition-delay: 1s;
}

or by using the shorthand property transition:

Example

div {
  transition: width 2s linear 1s;
}

Test Yourself With Exercises

Exercise:

Add a 2 second transition effect for width changes of the

element.

  
This is a div
 

 


CSS Transition Properties

The following table lists all the CSS transition properties:

Property Description
  A shorthand property for setting the four transition properties into a single property
  Specifies a delay (in seconds) for the transition effect
  Specifies how many seconds or milliseconds a transition effect takes to complete
  Specifies the name of the CSS property the transition effect is for
  Specifies the speed curve of the transition effect

 
CSS Transitions

 

CSS allows animation of HTML elements without using JavaScript or Flash!

CSS

In this chapter you will learn about the following properties:

  • @keyframes
  • animation-name
  • animation-duration
  • animation-delay
  • animation-iteration-count
  • animation-direction
  • animation-timing-function
  • animation-fill-mode
  • animation

Browser Support for Animations

The numbers in the table specify the first browser version that fully supports the property.

Property          
@keyframes 43.0 10.0 16.0 9.0 30.0
animation-name 43.0 10.0 16.0 9.0 30.0
animation-duration 43.0 10.0 16.0 9.0 30.0
animation-delay 43.0 10.0 16.0 9.0 30.0
animation-iteration-count 43.0 10.0 16.0 9.0 30.0
animation-direction 43.0 10.0 16.0 9.0 30.0
animation-timing-function 43.0 10.0 16.0 9.0 30.0
animation-fill-mode 43.0 10.0 16.0 9.0 30.0
animation 43.0 10.0 16.0 9.0 30.0

What are CSS Animations?

An animation lets an element gradually change from one style to another.

You can change as many CSS properties you want, as many times as you want.

To use CSS animation, you must first specify some keyframes for the animation.

Keyframes hold what styles the element will have at certain times.


The @keyframes Rule

When you specify CSS styles inside the @keyframes rule, the animation will gradually change from the current style to the new style at certain times.

To get an animation to work, you must bind the animation to an element.

The following example binds the "example" animation to the

element. The animation will last for 4 seconds, and it will gradually change the background-color of the
element from "red" to "yellow":

 

Example

/* The animation code */
@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}

/* The element to apply the animation to */
div {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
}

Note: The animation-duration property defines how long an animation should take to complete. If the animation-duration property is not specified, no animation will occur, because the default value is 0s (0 seconds). 

In the example above we have specified when the style will change by using the keywords "from" and "to" (which represents 0% (start) and 100% (complete)).

It is also possible to use percent. By using percent, you can add as many style changes as you like.

The following example will change the background-color of the

element when the animation is 25% complete, 50% complete, and again when the animation is 100% complete:

 

Example

/* The animation code */
@keyframes example {
  0%   {background-color: red;}
  25%  {background-color: yellow;}
  50%  {background-color: blue;}
  100% {background-color: green;}
}

/* The element to apply the animation to */
div {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
}

The following example will change both the background-color and the position of the

element when the animation is 25% complete, 50% complete, and again when the animation is 100% complete:

 

Example

/* The animation code */
@keyframes example {
  0%   {background-color:red; left:0px; top:0px;}
  25%  {background-color:yellow; left:200px; top:0px;}
  50%  {background-color:blue; left:200px; top:200px;}
  75%  {background-color:green; left:0px; top:200px;}
  100% {background-color:red; left:0px; top:0px;}
}

/* The element to apply the animation to */
div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
}


Delay an Animation

The animation-delay property specifies a delay for the start of an animation.

The following example has a 2 seconds delay before starting the animation:

Example

div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-delay: 2s;
}

Negative values are also allowed. If using negative values, the animation will start as if it had already been playing for N seconds.

In the following example, the animation will start as if it had already been playing for 2 seconds:

Example

div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-delay: -2s;
}

Set How Many Times an Animation Should Run

The animation-iteration-count property specifies the number of times an animation should run.

The following example will run the animation 3 times before it stops:

Example

div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: 3;
}

The following example uses the value "infinite" to make the animation continue for ever:

Example

div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

Run Animation in Reverse Direction or Alternate Cycles

The animation-direction property specifies whether an animation should be played forwards, backwards or in alternate cycles.

The animation-direction property can have the following values:

  • normal - The animation is played as normal (forwards). This is default
  • reverse - The animation is played in reverse direction (backwards)
  • alternate - The animation is played forwards first, then backwards
  • alternate-reverse - The animation is played backwards first, then forwards

The following example will run the animation in reverse direction (backwards):

Example

div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-direction: reverse;
}

The following example uses the value "alternate" to make the animation run forwards first, then backwards:

Example

div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: 2;
  animation-direction: alternate;
}

The following example uses the value "alternate-reverse" to make the animation run backwards first, then forwards:

Example

div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: 2;
  animation-direction: alternate-reverse;
}

Specify the Speed Curve of the Animation

The animation-timing-function property specifies the speed curve of the animation.

The animation-timing-function property can have the following values:

  • ease - Specifies an animation with a slow start, then fast, then end slowly (this is default)
  • linear - Specifies an animation with the same speed from start to end
  • ease-in - Specifies an animation with a slow start
  • ease-out - Specifies an animation with a slow end
  • ease-in-out - Specifies an animation with a slow start and end
  • cubic-bezier(n,n,n,n) - Lets you define your own values in a cubic-bezier function

The following example shows some of the different speed curves that can be used:

Example

#div1 {animation-timing-function: linear;}
#div2 {animation-timing-function: ease;}
#div3 {animation-timing-function: ease-in;}
#div4 {animation-timing-function: ease-out;}
#div5 {animation-timing-function: ease-in-out;}

Specify the fill-mode For an Animation

CSS animations do not affect an element before the first keyframe is played or after the last keyframe is played. The animation-fill-mode property can override this behavior.

The animation-fill-mode property specifies a style for the target element when the animation is not playing (before it starts, after it ends, or both).

The animation-fill-mode property can have the following values:

  • none - Default value. Animation will not apply any styles to the element before or after it is executing
  • forwards - The element will retain the style values that is set by the last keyframe (depends on animation-direction and animation-iteration-count)
  • backwards - The element will get the style values that is set by the first keyframe (depends on animation-direction), and retain this during the animation-delay period
  • both - The animation will follow the rules for both forwards and backwards, extending the animation properties in both directions

The following example lets the

element retain the style values from the last keyframe when the animation ends:

 

Example

div {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  animation-name: example;
  animation-duration: 3s;
  animation-fill-mode: forwards;
}

The following example lets the

element get the style values set by the first keyframe before the animation starts (during the animation-delay period):

 

Example

div {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  animation-name: example;
  animation-duration: 3s;
  animation-delay: 2s;
  animation-fill-mode: backwards;
}

The following example lets the

element get the style values set by the first keyframe before the animation starts, and retain the style values from the last keyframe when the animation ends:

 

Example

div {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  animation-name: example;
  animation-duration: 3s;
  animation-delay: 2s;
  animation-fill-mode: both;
}

Animation Shorthand Property

The example below uses six of the animation properties:

Example

div {
  animation-name: example;
  animation-duration: 5s;
  animation-timing-function: linear;
  animation-delay: 2s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

The same animation effect as above can be achieved by using the shorthand animation property:

Example

div {
  animation: example 5s linear 2s infinite alternate;
}

Test Yourself With Exercises

Exercise:

Add a 2 second animation for the

element, which changes the color from red to blue. Call the animation "example".

 



  
This is a div


 


CSS Animation Properties

The following table lists the @keyframes rule and all the CSS animation properties:

Property Description
  Specifies the animation code
  A shorthand property for setting all the animation properties
  Specifies a delay for the start of an animation
  Specifies whether an animation should be played forwards, backwards or in alternate cycles
  Specifies how long time an animation should take to complete one cycle
  Specifies a style for the element when the animation is not playing (before it starts, after it ends, or both)
  Specifies the number of times an animation should be played
  Specifies the name of the @keyframes animation
  Specifies whether the animation is running or paused
  Specifies the speed curve of the animation

 
CSS Animations
 

Create tooltips with CSS.


Demo: Tooltip Examples

A tooltip is often used to specify extra information about something when the user moves the mouse pointer over an element:

Top Tooltip text
Right Tooltip text
Bottom Tooltip text
Left Tooltip text

 


Basic Tooltip

Create a tooltip that appears when the user moves the mouse over an element:

Example



Hover over me
  Tooltip text

Example Explained

HTML: Use a container element (like

) and add the "tooltip" class to it. When the user mouse over this
, it will show the tooltip text.

 

The tooltip text is placed inside an inline element (like ) with class="tooltiptext".

CSS: The tooltip class use position:relative, which is needed to position the tooltip text (position:absolute). Note: See examples below on how to position the tooltip.

The tooltiptext class holds the actual tooltip text. It is hidden by default, and will be visible on hover (see below). We have also added some basic styles to it: 120px width, black background color, white text color, centered text, and 5px top and bottom padding.

The CSS border-radius property is used to add rounded corners to the tooltip text.

The :hover selector is used to show the tooltip text when the user moves the mouse over the

with class="tooltip".

 



Positioning Tooltips

In this example, the tooltip is placed to the right (left:105%) of the "hoverable" text (

). Also note that top:-5px is used to place it in the middle of its container element. We use the number 5 because the tooltip text has a top and bottom padding of 5px. If you increase its padding, also increase the value of the top property to ensure that it stays in the middle (if this is something you want). The same applies if you want the tooltip placed to the left.

 

Right Tooltip

.tooltip .tooltiptext {
  top: -5px;
  left: 105%;
}

Result:

Hover over me Tooltip text

Left Tooltip

.tooltip .tooltiptext {
  top: -5px;
  right: 105%;
}

Result:

Hover over me Tooltip text

If you want the tooltip to appear on top or on the bottom, see examples below. Note that we use the margin-left property with a value of minus 60 pixels. This is to center the tooltip above/below the hoverable text. It is set to the half of the tooltip's width (120/2 = 60).

Top Tooltip

.tooltip .tooltiptext {
  width: 120px;
  bottom: 100%;
  left: 50%;
  margin-left: -60px; /* Use half of the width (120/2 = 60), to center the tooltip */
}

Result:

Hover over me Tooltip text

Bottom Tooltip

.tooltip .tooltiptext {
  width: 120px;
  top: 100%;
  left: 50%;
  margin-left: -60px; /* Use half of the width (120/2 = 60), to center the tooltip */
}

Result:

Hover over me Tooltip text

Tooltip Arrows

To create an arrow that should appear from a specific side of the tooltip, add "empty" content after tooltip, with the pseudo-element class ::after together with the content property. The arrow itself is created using borders. This will make the tooltip look like a speech bubble.

This example demonstrates how to add an arrow to the bottom of the tooltip:

Bottom Arrow

.tooltip .tooltiptext::after {
  content: " ";
  position: absolute;
  top: 100%; /* At the bottom of the tooltip */
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: black transparent transparent transparent;
}

Result:

Hover over me Tooltip text

Example Explained

Position the arrow inside the tooltip: top: 100% will place the arrow at the bottom of the tooltip. left: 50% will center the arrow.

Note: The border-width property specifies the size of the arrow. If you change this, also change the margin-left value to the same. This will keep the arrow centered.

The border-color is used to transform the content into an arrow. We set the top border to black, and the rest to transparent. If all sides were black, you would end up with a black square box.

This example demonstrates how to add an arrow to the top of the tooltip. Notice that we set the bottom border color this time:

Top Arrow

.tooltip .tooltiptext::after {
  content: " ";
  position: absolute;
  bottom: 100%;  /* At the top of the tooltip */
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: transparent transparent black transparent;
}

Result:

Hover over me Tooltip text

This example demonstrates how to add an arrow to the left of the tooltip:

Left Arrow

.tooltip .tooltiptext::after {
  content: " ";
  position: absolute;
  top: 50%;
  right: 100%; /* To the left of the tooltip */
  margin-top: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: transparent black transparent transparent;
}

Result:

Hover over me Tooltip text

This example demonstrates how to add an arrow to the right of the tooltip:

Right Arrow

.tooltip .tooltiptext::after {
  content: " ";
  position: absolute;
  top: 50%;
  left: 100%; /* To the right of the tooltip */
  margin-top: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: transparent transparent transparent black;
}

Result:

Hover over me Tooltip text

Fade In Tooltips (Animation)

If you want to fade in the tooltip text when it is about to be visible, you can use the CSS transition property together with the opacity property, and go from being completely invisible to 100% visible, in a number of specified seconds (1 second in our example):

Example

.tooltip .tooltiptext {
  opacity: 0;
  transition: opacity 1s;
}

.tooltip:hover .tooltiptext {
  opacity: 1;
}

 
CSS Tooltips
 

Learn how to style images using CSS.


Rounded Images

Use the border-radius property to create rounded images:

 


Example

Rounded Image:

img {
  border-radius: 8px;
}

Example

Circled Image:

img {
  border-radius: 50%;
}

Thumbnail Images

Use the border property to create thumbnail images.

Thumbnail Image:


Example

img {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 5px;
  width: 150px;
}


Thumbnail Image as Link:

Example

img {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 5px;
  width: 150px;
}

img:hover {
  box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5);
}


  Paris


Responsive Images

Responsive images will automatically adjust to fit the size of the screen.

Resize the browser window to see the effect:

 

If you want an image to scale down if it has to, but never scale up to be larger than its original size, add the following:

Example

img {
  max-width: 100%;
  height: auto;
}

Tip: Read more about Responsive Web Design in our .


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: 50%;
}

Polaroid Images / Cards


Cinque Terre

Northern Lights

Example

div.polaroid {
  width: 80%;
  background-color: white;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

img {width: 100%}

div.container {
  text-align: center;
  padding: 10px 20px;
}

Transparent Image

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

Forest

opacity 0.2


opacity 0.5


opacity 1
(default)

Example

img {
  opacity: 0.5;
}

Image Text

How to position text in an image:

Example

Cingue Terre
Bottom Left
Top Left
Top Right
Bottom Right
Centered

Try it Yourself:


Image Filters

The CSS filter property adds visual effects (like blur and saturation) to an element.

Note: The filter property is not supported in Internet Explorer or Edge 12.

Example

Change the color of all images to black and white (100% gray):

img {
  filter: grayscale(100%);
}
 
Tip: Go to our to learn more about CSS filters.

Image Hover Overlay

Create an overlay effect on hover:

        Example

         Fade in text:


 

        Example

         Fade in a box:


          John

        Example

          Slide in (top):


 

       Example

         Slide in (bottom):


 

     Example

      Slide in (left):


 

     Example

      Slide in (right):


 

Flip an Image

Move your mouse over the image:

 


Example

img:hover {
  transform: scaleX(-1);
}

Responsive Image Gallery

CSS can be used to create image galleries. This example use media queries to re-arrange the images on different screen sizes. Resize the browser window to see the effect:

 
 

Example

.responsive {
  padding: 0 6px;
  float: left;
  width: 24.99999%;
}

@media only screen and (max-width: 700px){
  .responsive {
    width: 49.99999%;
    margin: 6px 0;
  }
}

@media only screen and (max-width: 500px){
  .responsive {
    width: 100%;
  }
}

Tip: Read more about Responsive Web Design in our .


Image Modal (Advanced)

This is an example to demonstrate how CSS and JavaScript can work together.

First, use CSS to create a modal window (dialog box), and hide it by default.

Then, use a JavaScript to show the modal window and to display the image inside the modal, when a user clicks on the image:

 

Example

// Get the modal
var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

// Get the element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}
 
CSS Style Images

 

The box-reflect property is used to create an image reflection.

The value of the box-reflect property can be: below, above, left , or right.


Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Numbers followed by -webkit- specify the first version that worked with a prefix.

Property          
box-reflect 4.0 -webkit- 79.0 -webkit- Not supported 4.0 -webkit- 15.0 -webkit-


Examples

Example

Here we want the reflection below the image:

img {
  -webkit-box-reflect: below;
}

Example

Here we want the reflection to the right of the image:

img {
  -webkit-box-reflect: right;
}

CSS Reflection Offset

To specify the gap between the image and the reflection, add the size of the gap to the box-reflect property.

Example

Here we want the reflection below the image, with a 20px offset:

img {
  -webkit-box-reflect: below 20px;
}

CSS Reflection With Gradient

We can also create a fade-out effect on the reflection.

Example

Create a fade-out effect on the reflection:

img {
  -webkit-box-reflect: below 0px linear-gradient(to bottom, rgba(0,0,0,0.0), rgba(0,0,0,0.4));
}
 
CSS Image Reflection

CSS The object-fit Property

 

The CSS object-fit property is used to specify how an or 


The CSS object-fit Property

The CSS object-fit property is used to specify how an or 

This property tells the content to fill the container in a variety of ways; such as "preserve that aspect ratio" or "stretch up and take up as much space as possible".

Look at the following image from Paris. This image is 400 pixels wide and 300 pixels high:

 

However, if we style the image above to be half its width (200 pixels) and same height (300 pixels), it will look like this:

 

Example

img {
  width: 200px;
  height: 300px;
}

We see that the image is being squished to fit the container of 200x300 pixels (its original aspect ratio is destroyed).

Here is where the object-fit property comes in. The object-fit property can take one of the following values:

  • fill - This is default. The image is resized to fill the given dimension. If necessary, the image will be stretched or squished to fit
  • contain - The image keeps its aspect ratio, but is resized to fit within the given dimension
  • cover - The image keeps its aspect ratio and fills the given dimension. The image will be clipped to fit
  • none - The image is not resized
  • scale-down - the image is scaled down to the smallest version of none or contain

Using object-fit: cover;

If we use object-fit: cover; the image keeps its aspect ratio and fills the given dimension. The image will be clipped to fit:

 

Example

img {
  width: 200px;
  height: 300px;
  object-fit: cover;
}


Using object-fit: contain;

If we use object-fit: contain; the image keeps its aspect ratio, but is resized to fit within the given dimension:

 

Example

img {
  width: 200px;
  height: 300px;
  object-fit: contain;
}

Using object-fit: fill;

If we use object-fit: fill; the image is resized to fill the given dimension. If necessary, the image will be stretched or squished to fit:

Example

img {
  width: 200px;
  height: 300px;
  object-fit: fill;
}

Using object-fit: none;

If we use object-fit: none; the image is not resized:

Paris

Example

img {
  width: 200px;
  height: 300px;
  object-fit: none;
}

Using object-fit: scale-down;

If we use object-fit: scale-down; the image is scaled down to the smallest version of none or contain:

 

Example

img {
  width: 200px;
  height: 300px;
  object-fit: scale-down;
}

Another Example

Here we have two images and we want them to fill the width of 50% of the browser window and 100% of the height.

In the following example we do NOT use object-fit, so when we resize the browser window, the aspect ratio of the images will be destroyed:

 
 

 CSS object-fit More Examples

The following example demonstrates all the possible values of the object-fit property in one example:

Example

.fill {object-fit: fill;}
.contain {object-fit: contain;}
.cover {object-fit: cover;}
.scale-down {object-fit: scale-down;}
.none {object-fit: none;}

CSS Object-* Properties

The following table lists the CSS object-* properties:

 

 
CSS object-fit

CSS The object-position Property

 

The CSS object-position property is used to specify how an or 


The Image

Look at the following image from Paris, which is 400x300 pixels:

 

Next, we use object-fit: cover; to keep the aspect ratio and to fill the given dimension. However, the image will be clipped to fit, like this:

 

Example

img {
  width: 200px;
  height: 300px;
  object-fit: cover;
}


Using the object-position Property

Let's say that the part of the image that is shown, is not positioned as we want. To position the image, we will use the object-position property.

Here we will use the object-position property to position the image so that the great old building is in center:

 

Example

img {
  width: 200px;
  height: 300px;
  object-fit: cover;
  object-position: 80% 100%;
}

Here we will use the object-position property to position the image so that the famous Eiffel Tower is in center:

 

Example

img {
  width: 200px;
  height: 300px;
  object-fit: cover;
  object-position: 15% 100%;
}

CSS Object-* Properties

The following table lists the CSS object-* properties:

 

 
 

With CSS masking you create a mask layer to place over an element to partially or fully hide portions of the element.


The CSS mask-image Property

The CSS mask-image property specifies a mask layer image.

The mask layer image can be a PNG image, an SVG image, a , or an .


Browser Support

Note: Most browsers only have partial support for CSS masking. You will need to use the -webkit- prefix in addition to the standard property in most browsers.

The numbers in the table below specify the first browser version that fully supports the property. Numbers followed by -webkit- specify the first version that worked with a prefix.

Property          
mask-image 4.0 -webkit- 79.0 -webkit- 53.0 4.0 -webkit- 15.0 -webkit-

Use an Image as the Mask Layer

To use a PNG or an SVG image as the mask layer, use a url() value to pass in the mask layer image.

The mask image needs to have a transparent or semi-transparent area. Black indicates fully transparent.

Here is the mask image (a PNG image) we will use:

 

Here is an image from Cinque Terre, in Italy:

 

Now, we apply the mask image (the PNG image above) as the mask layer for the image from Cinque Terre, Italy:

 

Example

Here is the source code:

.mask1 {
  -webkit-mask-image: url(w3logo.png);
  mask-image: url(w3logo.png);
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no-repeat;
}

Example Explained

The mask-image property specifies the image to be used as a mask layer for an element.

The mask-repeat property specifies if or how a mask image will be repeated. The no-repeat value indicates that the mask image will not be repeated (the mask image will only be shown once).

Another Example

If we omit the mask-repeat property, the mask image will be repeated all over the image from Cinque Terre, Italy:

 

Example

Here is the source code:

.mask1 {
  -webkit-mask-image: url(w3logo.png);
  mask-image: url(w3logo.png);
}


Use Gradients as the Mask Layer

CSS linear and radial gradients can also be used as mask images.

Linear Gradient Examples

Here, we use a linear-gradient as the mask layer for our image. This linear gradient goes from top (black) to bottom (transparent):


 

Example

Use a linear gradient as a mask layer:

.mask1 {
  -webkit-mask-image: linear-gradient(black, transparent);
  mask-image: linear-gradient(black, transparent);
}

Here, we use a linear-gradient along with text masking as the mask layer for our image:

The Cinque Terre is a coastal area within Liguria, in the northwest of Italy. It lies in the west of La Spezia Province, and comprises five villages: Monterosso al Mare, Vernazza, Corniglia, Manarola, and Riomaggiore.

The Cinque Terre is a coastal area within Liguria, in the northwest of Italy. It lies in the west of La Spezia Province, and comprises five villages: Monterosso al Mare, Vernazza, Corniglia, Manarola, and Riomaggiore.

The Cinque Terre is a coastal area within Liguria, in the northwest of Italy. It lies in the west of La Spezia Province, and comprises five villages: Monterosso al Mare, Vernazza, Corniglia, Manarola, and Riomaggiore.

Example

Use a linear gradient along with text masking as a mask layer:

.mask1 {
  max-width: 600px;
  height: 350px;
  overflow-y: scroll;
  background: url(img_5terre.jpg) no-repeat;
  -webkit-mask-image: linear-gradient(black, transparent);
  mask-image: linear-gradient (black, transparent);
}

Radial Gradient Examples

Here, we use a radial-gradient (shaped as a circle) as the mask layer for our image:

 

Example

Use a radial gradient as a mask layer (a circle):

.mask2 {
  -webkit-mask-image: radial-gradient(circle, black 50%, rgba(0, 0, 0, 0.5) 50%);
  mask-image: radial-gradient(circle, black 50%, rgba(0, 0, 0, 0.5) 50%);
}

Here, we use a radial-gradient (shaped as an ellipse) as the mask layer for our image:

Cinque Terre

Example

Use another radial gradient as a mask layer (an ellipse):

.mask3 {
  -webkit-mask-image: radial-gradient(ellipse, black 50%, rgba(0, 0, 0, 0.5) 50%);
  mask-image: radial-gradient(ellipse, black 50%, rgba(0, 0, 0, 0.5) 50%);
}

Use SVG as the Mask Layer

The SVG element can be used inside an SVG graphic to create masking effects.

Here, we use the SVG element to create different mask layers for our image:

Sorry, your browser does not support inline SVG.

Example

An SVG mask layer (formed as a triangle):


Sorry, your browser does not support inline SVG.

Example

An SVG mask layer (formed as a star):

Sorry, your browser does not support inline SVG.

Example

An SVG mask layer (formed as circles):
 


CSS Masking Properties

The following table lists all the CSS masking properties:

Property Description
  Specifies an image to be used as a mask layer for an element
  Specifies whether the mask layer image is treated as a luminance mask or as an alpha mask
  Specifies the origin position (the mask position area) of a mask layer image
  Sets the starting position of a mask layer image (relative to the mask position area)
  Specifies how the mask layer image is repeated
  Specifies the size of a mask layer image

 

 
CSS Masking
 

Learn how to style buttons using CSS.

 

Example

.button {
  background-color: #4CAF50; /* Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}

Button Colors

Use the background-color property to change the background color of a button:

Example

.button1 {background-color: #4CAF50;} /* Green */
.button2 {background-color: #008CBA;} /* Blue */
.button3 {background-color: #f44336;} /* Red */
.button4 {background-color: #e7e7e7; color: black;} /* Gray */
.button5 {background-color: #555555;} /* Black */


Button Sizes

Use the font-size property to change the font size of a button:

Example

.button1 {font-size: 10px;}
.button2 {font-size: 12px;}
.button3 {font-size: 16px;}
.button4 {font-size: 20px;}
.button5 {font-size: 24px;}

Use the padding property to change the padding of a button:

Example

.button1 {padding: 10px 24px;}
.button2 {padding: 12px 28px;}
.button3 {padding: 14px 40px;}
.button4 {padding: 32px 16px;}
.button5 {padding: 16px;}

Rounded Buttons

Use the border-radius property to add rounded corners to a button:

Example

.button1 {border-radius: 2px;}
.button2 {border-radius: 4px;}
.button3 {border-radius: 8px;}
.button4 {border-radius: 12px;}
.button5 {border-radius: 50%;}

Colored Button Borders

Use the border property to add a colored border to a button:

Example

.button1 {
  background-color: white;
  color: black;
  border: 2px solid #4CAF50; /* Green */
}
...

Hoverable Buttons


Use the :hover selector to change the style of a button when you move the mouse over it.

Tip: Use the transition-duration property to determine the speed of the "hover" effect:

Example

.button {
  transition-duration: 0.4s;
}

.button:hover {
  background-color: #4CAF50; /* Green */
  color: white;
}
...

Shadow Buttons

Use the box-shadow property to add shadows to a button:

Example

.button1 {
  box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
}

.button2:hover {
  box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
}

Disabled Buttons

Use the opacity property to add transparency to a button (creates a "disabled" look).

Tip: You can also add the cursor property with a value of "not-allowed", which will display a "no parking sign" when you mouse over the button:

Example

.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

Button Width


By default, the size of the button is determined by its text content (as wide as its content). Use the width property to change the width of a button:

Example

.button1 {width: 250px;}
.button2 {width: 50%;}
.button3 {width: 100%;}

Button Groups


Remove margins and add float:left to each button to create a button group:

Example

.button {
  float: left;
}

Bordered Button Group


Use the border property to create a bordered button group:

Example

.button {
  float: left;
  border: 1px solid green;
}

Vertical Button Group


Use display:block instead of float:left to group the buttons below each other, instead of side by side:

Example

.button {
  display: block;
}

Button on Image

 

Animated Buttons

Example

Add an arrow on hover:

Example

Add a "pressed" effect on click:

Example

Fade in on hover:

Example

Add a "ripple" effect on click:

 

 
CSS Buttons
 

Learn how to create a responsive pagination using CSS.


Simple Pagination

If you have a website with lots of pages, you may wish to add some sort of pagination to each page:

 

Example

.pagination {
  display: inline-block;
}

.pagination a {
  color: black;
  float: left;
  padding: 8px 16px;
  text-decoration: none;
}

Active and Hoverable Pagination

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="styles.css">
  <title>Pagination Example</title>
</head>
<body>

  <div class="pagination">
    <a href="#" class="active">1</a>
    <a href="#">2</a>
    <a href="#">3</a>
    <a href="#">4</a>
    <a href="#">5</a>
  </div>

</body>
</html>

 

Highlight the current page with an .active class, and use the :hover selector to change the color of each page link when moving the mouse over them:

Example

.pagination a.active {
  background-color: #4CAF50;
  color: white;
}

.pagination a:hover:not(.active) {background-color: #ddd;}

Rounded Active and Hoverable Buttons

.pagination {
  display: flex;
  list-style: none;
  padding: 0;
}

.pagination a {
  text-decoration: none;
  padding: 8px 12px;
  margin: 0 4px;
  border: 1px solid #ccc;
  color: #333;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.pagination a:hover {
  background-color: #eee;
}

.pagination a.active {
  background-color: #007bff;
  color: #fff;
}

Add the border-radius property if you want a rounded "active" and "hover" button:

Example

.pagination a {
  border-radius: 5px;
}

.pagination a.active {
  border-radius: 5px;
}

Hoverable Transition Effect

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .hover-effect {
      width: 200px;
      height: 100px;
      background-color: #3498db;
      color: #fff;
      text-align: center;
      line-height: 100px;
      transition: background-color 0.3s ease;
    }

    .hover-effect:hover {
      background-color: #2980b9;
    }
  </style>
  <title>Hoverable Transition Effect</title>
</head>
<body>

  <div class="hover-effect">Hover Me</div>

</body>
</html>

Add the transition property to the page links to create a transition effect on hover:

Example

.pagination a {
  transition: background-color .3s;
}


Bordered Pagination

  • Initial styles, such as background-color, color, and transition.
  • The transition property is used to specify the property to be transitioned (background-color), the duration of the transition (0.3s), and the timing function (ease).

Use the border property to add borders to the pagination:

Example

.pagination a {
  border: 1px solid #ddd; /* Gray */
}

Rounded Borders

Tip: Add rounded borders to your first and last link in the pagination:

 

Example

.pagination a:first-child {
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
}

.pagination a:last-child {
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
}

Space Between Links

Tip: Add the margin property if you do not want to group the page links:

 

Example

.pagination a {
  margin: 0 4px; /* 0 is for top and bottom. Feel free to change it */
}

Pagination Size

  • hange the size of the pagination with the font-size property:

Example

.pagination a {
  font-size: 22px;
}

To center the pagination, wrap a container element (like

) around it with text-align:center

 

Example

.center {
  text-align: center;
}

 

 

Breadcrumbs

 

Another variation of pagination is so-called "breadcrumbs":

Example

ul.breadcrumb {
  padding: 8px 16px;
  list-style: none;
  background-color: #eee;
}

ul.breadcrumb li {display: inline;}

ul.breadcrumb li+li:before {
  padding: 8px;
  color: black;
  content: "/�0a0";
}

 
CSS Pagination

CSS Multiple Columns


CSS Multi-column Layout

The CSS multi-column layout allows easy definition of multiple columns of text - just like in newspapers:

Daily Ping

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. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.


CSS Multi-column Properties

In this chapter you will learn about the following multi-column properties:

  • column-count
  • column-gap
  • column-rule-style
  • column-rule-width
  • column-rule-color
  • column-rule
  • column-span
  • column-width

Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Property
column-count 50.0 10.0 52.0 9.0 37.0
column-gap 50.0 10.0 52.0 9.0 37.0
column-rule 50.0 10.0 52.0 9.0 37.0
column-rule-color 50.0 10.0 52.0 9.0 37.0
column-rule-style 50.0 10.0 52.0 9.0 37.0
column-rule-width 50.0 10.0 52.0 9.0 37.0
column-span 50.0 10.0 71.0 9.0 37.0
column-width 50.0 10.0 52.0 9.0 37.0


CSS Create Multiple Columns

The column-count property specifies the number of columns an element should be divided into.

The following example will divide the text in the <div> element into 3 columns: 

Example

div {
  column-count: 3;
}

CSS Specify the Gap Between Columns

The column-gap property specifies the gap between the columns.

The following example specifies a 40 pixels gap between the columns:

Example

div {
  column-gap: 40px;
}

CSS Column Rules

The column-rule-style property specifies the style of the rule between columns:

Example

div {
  column-rule-style: solid;
}

The column-rule-width property specifies the width of the rule between columns:

Example

div {
  column-rule-width: 1px;
}

The column-rule-color property specifies the color of the rule between columns:

Example

div {
  column-rule-color: lightblue;
}

The column-rule property is a shorthand property for setting all the column-rule-* properties above.

The following example sets the width, style, and color of the rule between columns:

Example

div {
  column-rule: 1px solid lightblue;
}

Specify How Many Columns an Element Should Span

The column-span property specifies how many columns an element should span across.

The following example specifies that the <h2> element should span across all columns:

Example

h2 {
  column-span: all;
}

Specify The Column Width

The column-width property specifies a suggested, optimal width for the columns.

The following example specifies that the suggested, optimal width for the columns should be 100px:

Example

div {
  column-width: 100px;
}

CSS Multi-columns Properties

The following table lists all the multi-columns properties: 

Property Description
Specifies the number of columns an element should be divided into
Specifies how to fill columns
Specifies the gap between the columns
A shorthand property for setting all the column-rule-* properties
Specifies the color of the rule between columns
Specifies the style of the rule between columns
Specifies the width of the rule between columns
Specifies how many columns an element should span across
Specifies a suggested, optimal width for the columns
A shorthand property for setting column-width and column-count

CSS User Interface


CSS User Interface

In this chapter you will learn about the following CSS user interface properties:

  • resize
  • outline-offset

Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Property
resize 4.0 79.0 5.0 4.0 15.0
outline-offset 4.0 15.0 5.0 4.0 9.5

CSS Resizing

The resize property specifies if (and how) an element should be resizable by the user.

This div element is resizable by the user!

To resize: Click and drag the bottom right corner of this div element.

The following example lets the user resize only the width of a <div> element:

Example

div {
  resize: horizontal;
  overflow: auto;
}

The following example lets the user resize only the height of a <div> element:

Example

div {
  resize: vertical;
  overflow: auto;
}

The following example lets the user resize both the height and width of a <div> element:

Example

div {
  resize: both;
  overflow: auto;
}

In many browsers, <textarea> is resizable by default. Here, we have used the resize property to disable the resizability:

Example

textarea {
  resize: none;
}


CSS Outline Offset

The outline-offset property adds space between an outline and the edge or border of an element.

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

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.

The following example uses the outline-offset property to add space between the border and the outline:

Example

div.ex1 {
  margin: 20px;
  border: 1px solid black;
  outline: 4px solid red;
  outline-offset: 15px;
}

div.ex2 {
  margin: 10px;
  border: 1px solid black;
  outline: 5px dashed blue;
  outline-offset: 5px;
}

CSS User Interface Properties

The following table lists all the user interface properties:

Property Description
Adds space between an outline and the edge or border of an element
Specifies whether or not an element is resizable by the user


CSS Variables

The var() function is used to insert the value of a CSS variable.

CSS variables have access to the DOM, which means that you can create variables with local or global scope, change the variables with JavaScript, and change the variables based on media queries.

A good way to use CSS variables is when it comes to the colors of your design. Instead of copy and paste the same colors over and over again, you can place them in variables.


The Traditional Way

The following example shows the traditional way of defining some colors in a style sheet (by defining the colors to use, for each specific element):

Example

body { background-color: #1e90ff; }

h2 { border-bottom: 2px solid #1e90ff; }

.container {
  color: #1e90ff;
  background-color: #ffffff;
  padding: 15px;
}

button {
  background-color: #ffffff;
  color: #1e90ff;
  border: 1px solid #1e90ff;
  padding: 5px;
}


Syntax of the var() Function

The var() function is used to insert the value of a CSS variable.

The syntax of the var() function is as follows:

var(--name, value)
Value Description
name Required. The variable name (must start with two dashes)
value Optional. The fallback value (used if the variable is not found)

Note: The variable name must begin with two dashes (--) and it is case sensitive!



How var() Works

First of all: CSS variables can have a global or local scope.

Global variables can be accessed/used through the entire document, while local variables can be used only inside the selector where it is declared.

To create a variable with global scope, declare it inside the :root selector. The selector matches the document's root element.

To create a variable with local scope, declare it inside the selector that is going to use it.

The following example is equal to the example above, but here we use the var() function.

First, we declare two global variables (--blue and --white). Then, we use the var() function to insert the value of the variables later in the style sheet:

Example

:root {
  --blue: #1e90ff;
  --white: #ffffff;
}

body { background-color: var(--blue); }

h2 { border-bottom: 2px solid var(--blue); }

.container {
  color: var(--blue);
  background-color: var(--white);
  padding: 15px;
}

button {
  background-color: var(--white);
  color: var(--blue);
  border: 1px solid var(--blue);
  padding: 5px;
}

Advantages of using var() are:

  • makes the code easier to read (more understandable)
  • makes it much easier to change the color values

To change the blue and white color to a softer blue and white, you just need to change the two variable values:

Example

:root {
  --blue: #6495ed;
  --white: #faf0e6;
}

body { background-color: var(--blue); }

h2 { border-bottom: 2px solid var(--blue); }

.container {
  color: var(--blue);
  background-color: var(--white);
  padding: 15px;
}

button {
  background-color: var(--white);
  color: var(--blue);
  border: 1px solid var(--blue);
  padding: 5px;
}


Browser Support

The numbers in the table specify the first browser version that fully supports the var() function.

Function
var() 49.0 15.0 31.0 9.1 36.0

CSS var() Function

Property Description
Inserts the value of a CSS variable

 

CSS Variables

The var() function is used to insert the value of a CSS variable.

CSS variables have access to the DOM, which means that you can create variables with local or global scope, change the variables with JavaScript, and change the variables based on media queries.

A good way to use CSS variables is when it comes to the colors of your design. Instead of copy and paste the same colors over and over again, you can place them in variables.


The Traditional Way

The following example shows the traditional way of defining some colors in a style sheet (by defining the colors to use, for each specific element):

Example

body { background-color: #1e90ff; }

h2 { border-bottom: 2px solid #1e90ff; }

.container {
  color: #1e90ff;
  background-color: #ffffff;
  padding: 15px;
}

button {
  background-color: #ffffff;
  color: #1e90ff;
  border: 1px solid #1e90ff;
  padding: 5px;
}

Syntax of the var() Function

The var() function is used to insert the value of a CSS variable.

The syntax of the var() function is as follows:

var(--name, value)
Value Description
name Required. The variable name (must start with two dashes)
value Optional. The fallback value (used if the variable is not found)

Note: The variable name must begin with two dashes (--) and it is case sensitive!



How var() Works

First of all: CSS variables can have a global or local scope.

Global variables can be accessed/used through the entire document, while local variables can be used only inside the selector where it is declared.

To create a variable with global scope, declare it inside the :root selector. The selector matches the document's root element.

To create a variable with local scope, declare it inside the selector that is going to use it.

The following example is equal to the example above, but here we use the var() function.

First, we declare two global variables (--blue and --white). Then, we use the var() function to insert the value of the variables later in the style sheet:

Example

:root {
  --blue: #1e90ff;
  --white: #ffffff;
}

body { background-color: var(--blue); }

h2 { border-bottom: 2px solid var(--blue); }

.container {
  color: var(--blue);
  background-color: var(--white);
  padding: 15px;
}

button {
  background-color: var(--white);
  color: var(--blue);
  border: 1px solid var(--blue);
  padding: 5px;
}

Advantages of using var() are:

  • makes the code easier to read (more understandable)
  • makes it much easier to change the color values

To change the blue and white color to a softer blue and white, you just need to change the two variable values:

Example

:root {
  --blue: #6495ed;
  --white: #faf0e6;
}

body { background-color: var(--blue); }

h2 { border-bottom: 2px solid var(--blue); }

.container {
  color: var(--blue);
  background-color: var(--white);
  padding: 15px;
}

button {
  background-color: var(--white);
  color: var(--blue);
  border: 1px solid var(--blue);
  padding: 5px;
}

Browser Support

The numbers in the table specify the first browser version that fully supports the var() function.

Function          
var() 49.0 15.0 31.0 9.1 36.0

CSS var() Function

Property Description
  Inserts the value of a CSS variable

 

 
The var() Function
 

Override Global Variable With Local Variable

From the previous page we have learned that global variables can be accessed/used through the entire document, while local variables can be used only inside the selector where it is declared.

Look at the example from the previous page:

Example

:root {
  --blue: #1e90ff;
  --white: #ffffff;
}

body {
  background-color: var(--blue);
}

h2 {
  border-bottom: 2px solid var(--blue);
}

.container {
  color: var(--blue);
  background-color: var(--white);
  padding: 15px;
}

button {
  background-color: var(--white);
  color: var(--blue);
  border: 1px solid var(--blue);
  padding: 5px;
}

Sometimes we want the variables to change only in a specific section of the page.

Assume we want a different color of blue for button elements. Then, we can re-declare the --blue variable inside the button selector. When we use var(--blue) inside this selector, it will use the local --blue variable value declared here.

We see that the local --blue variable will override the global --blue variable for the button elements:

Example

:root {
  --blue: #1e90ff;
  --white: #ffffff;
}

body {
  background-color: var(--blue);
}

h2 {
  border-bottom: 2px solid var(--blue);
}

.container {
  color: var(--blue);
  background-color: var(--white);
  padding: 15px;
}

button {
  --blue: #0000ff; /* local variable will override global */
  background-color: var(--white);
  color: var(--blue);
  border: 1px solid var(--blue);
  padding: 5px;
}


Add a New Local Variable

If a variable is to be used at only one single place, we could also have declared a new local variable, like this:

Example

:root {
  --blue: #1e90ff;
  --white: #ffffff;
}

body {
  background-color: var(--blue);
}

h2 {
  border-bottom: 2px solid var(--blue);
}

.container {
  color: var(--blue);
  background-color: var(--white);
  padding: 15px;
}

button {
  --button-blue: #0000ff; /* new local variable */
  background-color: var(--white);
  color: var(--button-blue);
  border: 1px solid var(--button-blue);
  padding: 5px;
}

Browser Support

The numbers in the table specify the first browser version that fully supports the var() function.

Function          
var() 49.0 15.0 31.0 9.1 36.0

CSS var() Function

Property Description
  Inserts the value of a CSS variable

 

 
Overriding Variables
 

Change Variables With JavaScript

CSS variables have access to the DOM, which means that you can change them with JavaScript.

Here is an example of how you can create a script to display and change the --blue variable from the example used in the previous pages. For now, do not worry if you are not familiar with JavaScript. You can learn more about JavaScript in our :

Example

 

Browser Support

The numbers in the table specify the first browser version that fully supports the var() function.

Function          
var() 49.0 15.0 31.0 9.1 36.0

CSS var() Function

Property Description
  Inserts the value of a CSS variable

 

 
Variables and JavaScript
 

Using Variables in Media Queries

Now we want to change a variable value inside a media query.

Tip: Media Queries are about defining different style rules for different devices (screens, tablets, mobile phones, etc.). You can learn more Media Queries in our .

Here, we first declare a new local variable named --fontsize for the .container class. We set its value to 25 pixels. Then we use it in the .container class further down. Then, we create a @media rule that says "When the browser's width is 450px or wider, change the --fontsize variable value of the .container class to 50px."

Here is the complete example:

Example

/* Variable declarations */
:root {
  --blue: #1e90ff;
  --white: #ffffff;
}

.container {
  --fontsize: 25px;
}

/* Styles */
body {
  background-color: var(--blue);
}

h2 {
  border-bottom: 2px solid var(--blue);
}

.container {
  color: var(--blue);
  background-color: var(--white);
  padding: 15px;
  font-size: var(--fontsize);
}

@media screen and (min-width: 450px) {
  .container {
    --fontsize: 50px;
  }
}


Here is another example where we also change the value of the --blue variable in the @media rule:

Example

/* Variable declarations */
:root {
  --blue: #1e90ff;
  --white: #ffffff;
}

.container {
  --fontsize: 25px;
}

/* Styles */
body {
  background-color: var(--blue);
}

h2 {
  border-bottom: 2px solid var(--blue);
}

.container {
  color: var(--blue);
  background-color: var(--white);
  padding: 15px;
  font-size: var(--fontsize);
}

@media screen and (min-width: 450px) {
  .container {
    --fontsize: 50px;
  }
   :root {
    --blue: lightblue;
  }
}

Browser Support

The numbers in the table specify the first browser version that fully supports the var() function.

Function          
var() 49.0 15.0 31.0 9.1 36.0

CSS var() Function

Property Description
  Inserts the value of a CSS variable

 

 
Variables in Media Queries

CSS Box Sizing

 

CSS Box Sizing

The CSS box-sizing property allows us to include the padding and border in an element's total width and height.


Without the CSS box-sizing Property

By default, the width and height of an element is calculated like this:

width + padding + border = actual width of an element
height + padding + border = actual height of an element

This means: When you set the width/height of an element, the element often appears bigger than you have set (because the element's border and padding are added to the element's specified width/height).

The following illustration shows two

elements with the same specified width and height:

 

This div is smaller (width is 300px and height is 100px).

This div is bigger (width is also 300px and height is 100px).

The two

elements above end up with different sizes in the result (because div2 has a padding specified):

 

Example

.div1 {
  width: 300px;
  height: 100px;
  border: 1px solid blue;
}

.div2 {
  width: 300px;
  height: 100px;
  padding: 50px;
  border: 1px solid red;
}

The box-sizing property solves this problem.



With the CSS box-sizing Property

The box-sizing property allows us to include the padding and border in an element's total width and height.

If you set box-sizing: border-box; on an element, padding and border are included in the width and height:

Both divs are the same size now!

Hooray!

Here is the same example as above, with box-sizing: border-box; added to both

elements:

 

Example

.div1 {
  width: 300px;
  height: 100px;
  border: 1px solid blue;
  box-sizing: border-box;
}

.div2 {
  width: 300px;
  height: 100px;
  padding: 50px;
  border: 1px solid red;
  box-sizing: border-box;
}

Since the result of using the box-sizing: border-box; is so much better, many developers want all elements on their pages to work this way.

The code below ensures that all elements are sized in this more intuitive way. Many browsers already use box-sizing: border-box; for many form elements (but not all - which is why inputs and text areas look different at width: 100%;).

Applying this to all elements is safe and wise:

Example

* {
  box-sizing: border-box;
}

CSS Box Sizing Property

Property Description
  Defines how the width and height of an element are calculated: should they include padding and borders, or not

 
CSS Box Sizing

CSS Media Queries

 

CSS2 Introduced Media Types

The @media rule, introduced in CSS2, made it possible to define different style rules for different media types.

Examples: You could have one set of style rules for computer screens, one for printers, one for handheld devices, one for television-type devices, and so on.

Unfortunately these media types never got a lot of support by devices, other than the print media type.


CSS3 Introduced Media Queries

Media queries in CSS3 extended the CSS2 media types idea: Instead of looking for a type of device, they look at the capability of the device.

Media queries can be used to check many things, such as:

  • width and height of the viewport
  • width and height of the device
  • orientation (is the tablet/phone in landscape or portrait mode?)
  • resolution

Using media queries are a popular technique for delivering a tailored style sheet to desktops, laptops, tablets, and mobile phones (such as iPhone and Android phones).


Browser Support

The numbers in the table specifies the first browser version that fully supports the @media rule.

Property          
@media 21.0 9.0 3.5 4.0 9.0

Media Query Syntax

A media query consists of a media type and can contain one or more expressions, which resolve to either true or false.

@media not|only mediatype and (expressions) {
  CSS-Code;
}

The result of the query is true if the specified media type matches the type of device the document is being displayed on and all expressions in the media query are true. When a media query is true, the corresponding style sheet or style rules are applied, following the normal cascading rules.

Unless you use the not or only operators, the media type is optional and the all type will be implied.

You can also have different stylesheets for different media:

 


CSS3 Media Types

Value Description
all Used for all media type devices
print Used for printers
screen Used for computer screens, tablets, smart-phones etc.
speech Used for screenreaders that "reads" the page out loud

Media Queries Simple Examples

One way to use media queries is to have an alternate CSS section right inside your style sheet.

The following example changes the background-color to lightgreen if the viewport is 480 pixels wide or wider (if the viewport is less than 480 pixels, the background-color will be pink):

Example

@media screen and (min-width: 480px) {
  body {
    background-color: lightgreen;
  }
}

The following example shows a menu that will float to the left of the page if the viewport is 480 pixels wide or wider (if the viewport is less than 480 pixels, the menu will be on top of the content):

Example

@media screen and (min-width: 480px) {
  #leftsidebar {width: 200px; float: left;}
  #main {margin-left: 216px;}
}

More Media Query Examples

For much more examples on media queries, go to the next page: .


CSS @media Reference

For a full overview of all the media types and features/expressions, please look at the .

 

 
CSS Media Queries

CSS Media Queries - Examples

 

CSS Media Queries - More Examples

Let us look at some more examples of using media queries.

Media queries are a popular technique for delivering a tailored style sheet to different devices. To demonstrate a simple example, we can change the background color for different devices:

Example

/* Set the background color of body to tan */
body {
  background-color: tan;
}

/* On screens that are 992px or less, set the background color to blue */
@media screen and (max-width: 992px) {
  body {
    background-color: blue;
  }
}

/* On screens that are 600px or less, set the background color to olive */
@media screen and (max-width: 600px) {
  body {
    background-color: olive;
  }
}

Do you wonder why we use exactly 992px and 600px? They are what we call "typical breakpoints" for devices. You can read more about typical breakpoints in our .


Media Queries For Menus

In this example, we use media queries to create a responsive navigation menu, that varies in design on different screen sizes.

Large screens:

 

Small screens:

 

Example

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

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

/* On screens that are 600px wide or less, make the menu links stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) {
  .topnav a {
    float: none;
    width: 100%;
  }
}


Media Queries For Columns

A common use of media queries, is to create a flexible layout. In this example, we create a layout that varies between four, two and full-width columns, depending on different screen sizes:

Large screens:

 
 
 
 

 

Medium screens:

 
 

 

Small screens:

 

Example

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

/* On screens that are 992px wide or less, go from four columns to two columns */
@media screen and (max-width: 992px) {
  .column {
    width: 50%;
  }
}

/* On screens that are 600px wide or less, make the columns stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) {
  .column {
    width: 100%;
  }
}

Tip: A more modern way of creating column layouts, is to use CSS Flexbox (see example below). However, it is not supported in Internet Explorer 10 and earlier versions. If you require IE6-10 support, use floats (as shown above).

To learn more about the Flexible Box Layout Module, .

To learn more about Responsive Web Design, .

Example

/* Container for flexboxes */
.row {
  display: flex;
  flex-wrap: wrap;
}

/* Create four equal columns */
.column {
  flex: 25%;
  padding: 20px;
}

/* On screens that are 992px wide or less, go from four columns to two columns */
@media screen and (max-width: 992px) {
  .column {
    flex: 50%;
  }
}

/* On screens that are 600px wide or less, make the columns stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) {
  .row {
    flex-direction: column;
  }
}

Hide Elements With Media Queries

Another common use of media queries, is to hide elements on different screen sizes:

I will be hidden on small screens.

Example

/* If the screen size is 600px wide or less, hide the element */
@media screen and (max-width: 600px) {
  div.example {
    display: none;
  }
}

Change Font Size With Media Queries

You can also use media queries to change the font size of an element on different screen sizes:

 

Example

* If screen size is more than 600px wide, set the font-size of
to 80px */
@media screen and (min-width: 600px) {
  div.example {
    font-size: 80px;
  }
}

/* If screen size is 600px wide, or less, set the font-size of
to 30px */
@media screen and (max-width: 600px) {
  div.example {
    font-size: 30px;
  }
}

Flexible Image Gallery

In this example, we use media queries together with flexbox to create a responsive image gallery:


 

Orientation: Portrait / Landscape

Media queries can also be used to change layout of a page depending on the orientation of the browser.

You can have a set of CSS properties that will only apply when the browser window is wider than its height, a so called "Landscape" orientation:

Example

Use a lightblue background color if the orientation is in landscape mode:

@media only screen and (orientation: landscape) {
  body {
    background-color: lightblue;
  }
}

Min Width to Max Width

You can also use the (max-width: ..) and (min-width: ..) values to set a minimum width and a maximum width.

For example, when the browser's width is between 600 and 900px, change the appearance of a

element:

 

Example

@media screen and (max-width: 900px) and (min-width: 600px) {
  div.example {
    font-size: 50px;
    padding: 50px;
    border: 8px solid black;
    background: yellow;
  }
}

Using an additional value: In the example below, we add an additional media query to our already existing one using a comma (this will behave like an OR operator):

Example

/* When the width is between 600px and 900px OR above 1100px - change the appearance of
*/
@media screen and (max-width: 900px) and (min-width: 600px), (min-width: 1100px) {
  div.example {
    font-size: 50px;
    padding: 50px;
    border: 8px solid black;
    background: yellow;
  }
}

CSS @media Reference

For a full overview of all the media types and features/expressions, please look at the .

Tip: To learn more about responsive web design (how to target different devices and screens), using media query breakpoints, read our .


 
CSS MQ Examples

CSS Flexbox

 

 

CSS Flexbox Layout Module

 

Before the Flexbox Layout module, there were four layout modes:

  • Block, for sections in a webpage
  • Inline, for text
  • Table, for two-dimensional table data
  • Positioned, for explicit position of an element

The Flexible Box Layout Module, makes it easier to design flexible responsive layout structure without using float or positioning.


Browser Support

The flexbox properties are supported in all modern browsers.

         
29.0 11.0 22.0 10 48

Flexbox Elements

To start using the Flexbox model, you need to first define a flex container.

 

The element above represents a flex container (the blue area) with three flex items.

Example

A flex container with three flex items:

 

You will learn more about flex containers and flex items in the next chapters.

 

 
CSS Flexbox

CSS Flexbox


2

3

4

5

6

7

8


CSS Flexbox Layout Module

Before the Flexbox Layout module, there were four layout modes:

  • Block, for sections in a webpage
  • Inline, for text
  • Table, for two-dimensional table data
  • Positioned, for explicit position of an element

The Flexible Box Layout Module, makes it easier to design flexible responsive layout structure without using float or positioning.


Browser Support

The flexbox properties are supported in all modern browsers.

29.0 11.0 22.0 10 48

Flexbox Elements

To start using the Flexbox model, you need to first define a flex container.

1

2

3

The element above represents a flex container (the blue area) with three flex items.

Example

A flex container with three flex items:

<div class="flex-container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
</div>

You will learn more about flex containers and flex items in the next chapters.


 

Parent Element (Container)

Like we specified in the previous chapter, this is a flex container (the blue area) with three flex items:

 
 

The flex container becomes flexible by setting the display property to flex:

Example

.flex-container {
  display: flex;
}

 

The flex container properties are:

 


 

The flex-direction Property

The flex-direction property defines in which direction the container wants to stack the flex items.

 

Example

The column value stacks the flex items vertically (from top to bottom):

.flex-container {
  display: flex;
  flex-direction: column;
}

 

Example

The column-reverse value stacks the flex items vertically (but from bottom to top):

.flex-container {
  display: flex;
  flex-direction: column-reverse;
}

 

Example

The row value stacks the flex items horizontally (from left to right):

.flex-container {
  display: flex;
  flex-direction: row;
}

 

Example

The row-reverse value stacks the flex items horizontally (but from right to left):

.flex-container {
  display: flex;
  flex-direction: row-reverse;
}

 


 

The flex-wrap Property

The flex-wrap property specifies whether the flex items should wrap or not.

The examples below have 12 flex items, to better demonstrate the flex-wrap property.

 

 

Example

The wrap value specifies that the flex items will wrap if necessary:

.flex-container {
  display: flex;
  flex-wrap: wrap;
}

 

Example

The nowrap value specifies that the flex items will not wrap (this is default):

.flex-container {
  display: flex;
  flex-wrap: nowrap;
}

 

Example

The wrap-reverse value specifies that the flexible items will wrap if necessary, in reverse order:

.flex-container {
  display: flex;
  flex-wrap: wrap-reverse;
}

 


 

The flex-flow Property

The flex-flow property is a shorthand property for setting both the flex-direction and flex-wrap properties.

Example

.flex-container {
  display: flex;
  flex-flow: row wrap;
}

 


 

The justify-content Property

The justify-content property is used to align the flex items:

 

Example

The center value aligns the flex items at the center of the container:

.flex-container {
  display: flex;
  justify-content: center;
}

 

Example

The flex-start value aligns the flex items at the beginning of the container (this is default):

.flex-container {
  display: flex;
  justify-content: flex-start;
}

 

Example

The flex-end value aligns the flex items at the end of the container:

.flex-container {
  display: flex;
  justify-content: flex-end;
}

 

Example

The space-around value displays the flex items with space before, between, and after the lines:

.flex-container {
  display: flex;
  justify-content: space-around;
}

 

Example

The space-between value displays the flex items with space between the lines:

.flex-container {
  display: flex;
  justify-content: space-between;
}

 


 

The align-items Property

The align-items property is used to align the flex items.

 

In these examples we use a 200 pixels high container, to better demonstrate the align-items property.

Example

The center value aligns the flex items in the middle of the container:

.flex-container {
  display: flex;
  height: 200px;
  align-items: center;
}

 

Example

The flex-start value aligns the flex items at the top of the container:

.flex-container {
  display: flex;
  height: 200px;
  align-items: flex-start;
}

 

Example

The flex-end value aligns the flex items at the bottom of the container:

.flex-container {
  display: flex;
  height: 200px;
  align-items: flex-end;
}

 

Example

The stretch value stretches the flex items to fill the container (this is default):

.flex-container {
  display: flex;
  height: 200px;
  align-items: stretch;
}

 

Example

The baseline value aligns the flex items such as their baselines aligns:

.flex-container {
  display: flex;
  height: 200px;
  align-items: baseline;
}

Note: the example uses different font-size to demonstrate that the items gets aligned by the text baseline:


 
 
 
 

 


 

The align-content Property

The align-content property is used to align the flex lines.

In these examples we use a 600 pixels high container, with the flex-wrap property set to wrap, to better demonstrate the align-content property.

Example

The space-between value displays the flex lines with equal space between them:

.flex-container {
  display: flex;
  height: 600px;
  flex-wrap: wrap;
  align-content: space-between;
}

 

Example

The space-around value displays the flex lines with space before, between, and after them:

.flex-container {
  display: flex;
  height: 600px;
  flex-wrap: wrap;
  align-content: space-around;
}

 

Example

The stretch value stretches the flex lines to take up the remaining space (this is default):

.flex-container {
  display: flex;
  height: 600px;
  flex-wrap: wrap;
  align-content: stretch;
}

 

Example

The center value displays the flex lines in the middle of the container:

.flex-container {
  display: flex;
  height: 600px;
  flex-wrap: wrap;
  align-content: center;
}

 

Example

The flex-start value displays the flex lines at the start of the container:

.flex-container {
  display: flex;
  height: 600px;
  flex-wrap: wrap;
  align-content: flex-start;
}

 

Example

The flex-end value displays the flex lines at the end of the container: 

.flex-container {
  display: flex;
  height: 600px;
  flex-wrap: wrap;
  align-content: flex-end;
}

 


Perfect Centering

In the following example we will solve a very common style problem: perfect centering.

 

SOLUTION: Set both the justify-content and align-items properties to center, and the flex item will be perfectly centered:

Example

.flex-container {
  display: flex;
  height: 300px;
  justify-content: center;
  align-items: center;
}

 


The CSS Flexbox Container Properties

The following table lists all the CSS Flexbox Container properties:

Property Description
  Modifies the behavior of the flex-wrap property. It is similar to align-items, but instead of aligning flex items, it aligns flex lines
  Vertically aligns the flex items when the items do not use all available space on the cross-axis
  Specifies the type of box used for an HTML element
  Specifies the direction of the flexible items inside a flex container
  A shorthand property for flex-direction and flex-wrap
  Specifies whether the flex items should wrap or not, if there is not enough room for them on one flex line
  Horizontally aligns the flex items when the items do not use all available space on the main-axis

 

 
CSS Flex Container

Child Elements (Items)

The direct child elements of a flex container automatically becomes flexible (flex) items.

1

2

3

4

The element above represents four blue flex items inside a grey flex container.

Example

<div class="flex-container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

The flex item properties are:


The order Property

The order property specifies the order of the flex items.

1

2

3

4

The first flex item in the code does not have to appear as the first item in the layout.

The order value must be a number, default value is 0.

Example

The order property can change the order of the flex items:

<div class="flex-container">
  <div style="order: 3">1</div>
  <div style="order: 2">2</div>
  <div style="order: 4">3</div>
  <div style="order: 1">4</div>
</div>


The flex-grow Property

The flex-grow property specifies how much a flex item will grow relative to the rest of the flex items.

1

2

3

The value must be a number, default value is 0.

Example

Make the third flex item grow eight times faster than the other flex items:

<div class="flex-container">
  <div style="flex-grow: 1">1</div>
  <div style="flex-grow: 1">2</div>
  <div style="flex-grow: 8">3</div>
</div>



The flex-shrink Property

The flex-shrink property specifies how much a flex item will shrink relative to the rest of the flex items.

1

2

3

4

5

6

7

8

9

10

The value must be a number, default value is 1.

Example

Do not let the third flex item shrink as much as the other flex items:

<div class="flex-container">
  <div>1</div>
  <div>2</div>
  <div style="flex-shrink: 0">3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
  <div>10</div>
</div>


The flex-basis Property

The flex-basis property specifies the initial length of a flex item.

1

2

3

4

Example

Set the initial length of the third flex item to 200 pixels:

<div class="flex-container">
  <div>1</div>
  <div>2</div>
  <div style="flex-basis: 200px">3</div>
  <div>4</div>
</div>


The flex Property

The flex property is a shorthand property for the flex-grow, flex-shrink, and flex-basis properties.

Example

Make the third flex item not growable (0), not shrinkable (0), and with an initial length of 200 pixels:

<div class="flex-container">
  <div>1</div>
  <div>2</div>
  <div style="flex: 0 0 200px">3</div>
  <div>4</div>
</div>


The align-self Property

The align-self property specifies the alignment for the selected item inside the flexible container.

The align-self property overrides the default alignment set by the container's align-items property.

1

2

3

4

In these examples we use a 200 pixels high container, to better demonstrate the align-self property:

Example

Align the third flex item in the middle of the container:

<div class="flex-container">
  <div>1</div>
  <div>2</div>
  <div style="align-self: center">3</div>
  <div>4</div>
</div>

Example

Align the second flex item at the top of the container, and the third flex item at the bottom of the container:

<div class="flex-container">
  <div>1</div>
  <div style="align-self: flex-start">2</div>
  <div style="align-self: flex-end">3</div>
  <div>4</div>
</div>


The CSS Flexbox Items Properties

The following table lists all the CSS Flexbox Items properties:

Property Description
Specifies the alignment for a flex item (overrides the flex container's align-items property)
A shorthand property for the flex-grow, flex-shrink, and the flex-basis properties
Specifies the initial length of a flex item
Specifies how much a flex item will grow relative to the rest of the flex items inside the same container
Specifies how much a flex item will shrink relative to the rest of the flex items inside the same container
Specifies the order of the flex items inside the same container


Responsive Flexbox

You learned from the chapter that you can use media queries to create different layouts for different screen sizes and devices.

Laptop and Desktops:

1
2
3

Mobile phones and Tablets:

1
2
3

For example, if you want to create a two-column layout for most screen sizes, and a one-column layout for small screen sizes (such as phones and tablets), you can change the flex-direction from row to column at a specific breakpoint (800px in the example below):

Example

.flex-container {
  display: flex;
  flex-direction: row;
}

/* Responsive layout - makes a one column layout instead of a two-column layout */
@media (max-width: 800px) {
  .flex-container {
    flex-direction: column;
  }
}

Another way is to change the percentage of the flex property of the flex items to create different layouts for different screen sizes. Note that we also have to include flex-wrap: wrap; on the flex container for this example to work:

Example

.flex-container {
  display: flex;
  flex-wrap: wrap;
}

.flex-item-left {
  flex: 50%;
}

.flex-item-right {
  flex: 50%;
}

/* Responsive layout - makes a one column layout instead of a two-column layout */
@media (max-width: 800px) {
  .flex-item-right, .flex-item-left {
    flex: 100%;
  }
}



Responsive Image Gallery using Flexbox

Use flexbox to create a responsive image gallery that varies between four, two or full-width images, depending on screen size:


Responsive Website using Flexbox

Use flexbox to create a responsive website, containing a flexible navigation bar and flexible content:




Responsive Web Design - Introduction


What is Responsive Web Design?

Responsive web design makes your web page look good on all devices.

Responsive web design uses only HTML and CSS.

Responsive web design is not a program or a JavaScript.


Designing For The Best Experience For All Users

Web pages can be viewed using many different devices: desktops, tablets, and phones. Your web page should look good, and be easy to use, regardless of the device.

Web pages should not leave out information to fit smaller devices, but rather adapt its content to fit any device:



Desktop

Tablet

Phone

It is called responsive web design when you use CSS and HTML to resize, hide, shrink, enlarge, or move the content to make it look good on any screen.

Don't worry if you don't understand the example below, we will break down the code, step-by-step, in the next chapters:



Responsive Web Design - The Viewport


What is The Viewport?

The viewport is the user's visible area of a web page.

The viewport varies with the device, and will be smaller on a mobile phone than on a computer screen.

Before tablets and mobile phones, web pages were designed only for computer screens, and it was common for web pages to have a static design and a fixed size.

Then, when we started surfing the internet using tablets and mobile phones, fixed size web pages were too large to fit the viewport. To fix this, browsers on those devices scaled down the entire web page to fit the screen.

This was not perfect!! But a quick fix.


Setting The Viewport

HTML5 introduced a method to let web designers take control over the viewport, through the <meta> tag.

You should include the following <meta> viewport element in all your web pages:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

This gives the browser instructions on how to control the page's dimensions and scaling.

The width=device-width part sets the width of the page to follow the screen-width of the device (which will vary depending on the device).

The initial-scale=1.0 part sets the initial zoom level when the page is first loaded by the browser.

Here is an example of a web page without the viewport meta tag, and the same web page with the viewport meta tag:






Tip: If you are browsing this page with a phone or a tablet, you can click on the two links above to see the difference.


Size Content to The Viewport

Users are used to scroll websites vertically on both desktop and mobile devices - but not horizontally!

So, if the user is forced to scroll horizontally, or zoom out, to see the whole web page it results in a poor user experience.

Some additional rules to follow:

1. Do NOT use large fixed width elements - For example, if an image is displayed at a width wider than the viewport it can cause the viewport to scroll horizontally. Remember to adjust this content to fit within the width of the viewport.

2. Do NOT let the content rely on a particular viewport width to render well - Since screen dimensions and width in CSS pixels vary widely between devices, content should not rely on a particular viewport width to render well.

3. Use CSS media queries to apply different styling for small and large screens - Setting large absolute CSS widths for page elements will cause the element to be too wide for the viewport on a smaller device. Instead, consider using relative width values, such as width: 100%. Also, be careful of using large absolute positioning values. It may cause the element to fall outside the viewport on small devices.


Responsive Web Design - Grid-View


What is a Grid-View?

Many web pages are based on a grid-view, which means that the page is divided into columns:


Using a grid-view is very helpful when designing web pages. It makes it easier to place elements on the page.


A responsive grid-view often has 12 columns, and has a total width of 100%, and will shrink and expand as you resize the browser window.



Building a Responsive Grid-View

Lets start building a responsive grid-view.

First ensure that all HTML elements have the box-sizing property set to border-box. This makes sure that the padding and border are included in the total width and height of the elements.

Add the following code in your CSS:

* {
  box-sizing: border-box;
}

Read more about the box-sizing property in our chapter.

The following example shows a simple responsive web page, with two columns:

25%
75%

Example

.menu {
  width: 25%;
  float: left;
}
.main {
  width: 75%;
  float: left;
}

The example above is fine if the web page only contains two columns.

However, we want to use a responsive grid-view with 12 columns, to have more control over the web page.

First we must calculate the percentage for one column: 100% / 12 columns = 8.33%.

Then we make one class for each of the 12 columns, class="col-" and a number defining how many columns the section should span:

CSS:

.col-1 {width: 8.33%;}
.col-2 {width: 16.66%;}
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}

 All these columns should be floating to the left, and have a padding of 15px:

CSS:

[class*="col-"] {
  float: left;
  padding: 15px;
  border: 1px solid red;
}

Each row should be wrapped in a <div>. The number of columns inside a row should always add up to 12:

HTML:

<div class="row">
  <div class="col-3">...</div> <!-- 25% -->
  <div class="col-9">...</div> <!-- 75% -->
</div>

The columns inside a row are all floating to the left, and are therefore taken out of the flow of the page, and other elements will be placed as if the columns do not exist. To prevent this, we will add a style that clears the flow:

CSS:

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

We also want to add some styles and colors to make it look better:

Example

html {
  font-family: "Lucida Sans", sans-serif;
}

.header {
  background-color: #9933cc;
  color: #ffffff;
  padding: 15px;
}

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

.menu li {
  padding: 8px;
  margin-bottom: 7px;
  background-color :#33b5e5;
  color: #ffffff;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

.menu li:hover {
  background-color: #0099cc;
}

Notice that the webpage in the example does not look good when you resize the browser window to a very small width. In the next chapter you will learn how to fix that.


Responsive Web Design - Media Queries


What is a Media Query?

Media query is a CSS technique introduced in CSS3.

It uses the @media rule to include a block of CSS properties only if a certain condition is true.

Example

If the browser window is 600px or smaller, the background color will be lightblue:

@media only screen and (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}

Add a Breakpoint

Earlier in this tutorial we made a web page with rows and columns, and it was responsive, but it did not look good on a small screen.

Media queries can help with that. We can add a breakpoint where certain parts of the design will behave differently on each side of the breakpoint.


Desktop

Phone

Use a media query to add a breakpoint at 768px:

Example

When the screen (browser window) gets smaller than 768px, each column should have a width of 100%:

/* For desktop: */
.col-1 {width: 8.33%;}
.col-2 {width: 16.66%;}
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}

@media only screen and (max-width: 768px) {
  /* For mobile phones: */
  [class*="col-"] {
    width: 100%;
  }
}


Always Design for Mobile First

Mobile First means designing for mobile before designing for desktop or any other device (This will make the page display faster on smaller devices).

This means that we must make some changes in our CSS.

Instead of changing styles when the width gets smaller than 768px, we should change the design when the width gets larger than 768px. This will make our design Mobile First:

Example

/* For mobile phones: */
[class*="col-"] {
  width: 100%;
}

@media only screen and (min-width: 768px) {
  /* For desktop: */
  .col-1 {width: 8.33%;}
  .col-2 {width: 16.66%;}
  .col-3 {width: 25%;}
  .col-4 {width: 33.33%;}
  .col-5 {width: 41.66%;}
  .col-6 {width: 50%;}
  .col-7 {width: 58.33%;}
  .col-8 {width: 66.66%;}
  .col-9 {width: 75%;}
  .col-10 {width: 83.33%;}
  .col-11 {width: 91.66%;}
  .col-12 {width: 100%;}
}

Another Breakpoint

You can add as many breakpoints as you like.

We will also insert a breakpoint between tablets and mobile phones.


Desktop

Tablet

Phone

We do this by adding one more media query (at 600px), and a set of new classes for devices larger than 600px (but smaller than 768px):

Example

Note that the two sets of classes are almost identical, the only difference is the name (col- and col-s-):

/* For mobile phones: */
[class*="col-"] {
  width: 100%;
}

@media only screen and (min-width: 600px) {
  /* For tablets: */
  .col-s-1 {width: 8.33%;}
  .col-s-2 {width: 16.66%;}
  .col-s-3 {width: 25%;}
  .col-s-4 {width: 33.33%;}
  .col-s-5 {width: 41.66%;}
  .col-s-6 {width: 50%;}
  .col-s-7 {width: 58.33%;}
  .col-s-8 {width: 66.66%;}
  .col-s-9 {width: 75%;}
  .col-s-10 {width: 83.33%;}
  .col-s-11 {width: 91.66%;}
  .col-s-12 {width: 100%;}
}

@media only screen and (min-width: 768px) {
  /* For desktop: */
  .col-1 {width: 8.33%;}
  .col-2 {width: 16.66%;}
  .col-3 {width: 25%;}
  .col-4 {width: 33.33%;}
  .col-5 {width: 41.66%;}
  .col-6 {width: 50%;}
  .col-7 {width: 58.33%;}
  .col-8 {width: 66.66%;}
  .col-9 {width: 75%;}
  .col-10 {width: 83.33%;}
  .col-11 {width: 91.66%;}
  .col-12 {width: 100%;}
}

It might seem odd that we have two sets of identical classes, but it gives us the opportunity in HTML, to decide what will happen with the columns at each breakpoint:

HTML Example

For desktop:

The first and the third section will both span 3 columns each. The middle section will span 6 columns.

For tablets:

The first section will span 3 columns, the second will span 9, and the third section will be displayed below the first two sections, and it will span 12 columns:

<div class="row">
  <div class="col-3 col-s-3">...</div>
  <div class="col-6 col-s-9">...</div>
  <div class="col-3 col-s-12">...</div>
</div>

Typical Device Breakpoints

There are tons of screens and devices with different heights and widths, so it is hard to create an exact breakpoint for each device. To keep things simple you could target five groups:

Example

/* Extra small devices (phones, 600px and down) */
@media only screen and (max-width: 600px) {...}

/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px) {...}

/* Medium devices (landscape tablets, 768px and up) */
@media only screen and (min-width: 768px) {...}

/* Large devices (laptops/desktops, 992px and up) */
@media only screen and (min-width: 992px) {...}

/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) {...}

Orientation: Portrait / Landscape

Media queries can also be used to change layout of a page depending on the orientation of the browser.

You can have a set of CSS properties that will only apply when the browser window is wider than its height, a so called "Landscape" orientation:

Example

The web page will have a lightblue background if the orientation is in landscape mode:

@media only screen and (orientation: landscape) {
  body {
    background-color: lightblue;
  }
}

Hide Elements With Media Queries

Another common use of media queries, is to hide elements on different screen sizes:

I will be hidden on small screens.

Example

/* If the screen size is 600px wide or less, hide the element */
@media only screen and (max-width: 600px) {
  div.example {
    display: none;
  }
}

Change Font Size With Media Queries

You can also use media queries to change the font size of an element on different screen sizes:

Example

/* If the screen size is 601px or more, set the font-size of <div> to 80px */
@media only screen and (min-width: 601px) {
  div.example {
    font-size: 80px;
  }
}

/* If the screen size is 600px or less, set the font-size of <div> to 30px */
@media only screen and (max-width: 600px) {
  div.example {
    font-size: 30px;
  }
}

CSS @media Reference

For a full overview of all the media types and features/expressions, please look at the .


Responsive Web Design - Images

 

Resize the browser window to see how the image scales to fit the page.


Using The width Property

If the width property is set to a percentage and the height property is set to "auto", the image will be responsive and scale up and down:

Example

img {
  width: 100%;
  height: auto;
}

Notice that in the example above, the image can be scaled up to be larger than its original size. A better solution, in many cases, will be to use the max-width property instead.


Using The max-width Property

If the max-width property is set to 100%, the image will scale down if it has to, but never scale up to be larger than its original size:

Example

img {
  max-width: 100%;
  height: auto;
}

Add an Image to The Example Web Page

Example

img {
  width: 100%;
  height: auto;
}


Background Images

Background images can also respond to resizing and scaling.

Here we will show three different methods:

1. If the background-size property is set to "contain", the background image will scale, and try to fit the content area. However, the image will keep its aspect ratio (the proportional relationship between the image's width and height):

 

 

Here is the CSS code:

Example

div {
  width: 100%;
  height: 400px;
  background-image: url('img_flowers.jpg');
  background-repeat: no-repeat;
  background-size: contain;
  border: 1px solid red;
}

2. If the background-size property is set to "100% 100%", the background image will stretch to cover the entire content area:

 

 

Here is the CSS code:

Example

div {
  width: 100%;
  height: 400px;
  background-image: url('img_flowers.jpg');
  background-size: 100% 100%;
  border: 1px solid red;
}

3. If the background-size property is set to "cover", the background image will scale to cover the entire content area. Notice that the "cover" value keeps the aspect ratio, and some part of the background image may be clipped:

 

 

Here is the CSS code:

Example

div {
  width: 100%;
  height: 400px;
  background-image: url('img_flowers.jpg');
  background-size: cover;
  border: 1px solid red;
}

Different Images for Different Devices

A large image can be perfect on a big computer screen, but useless on a small device. Why load a large image when you have to scale it down anyway? To reduce the load, or for any other reasons, you can use media queries to display different images on different devices.

Here is one large image and one smaller image that will be displayed on different devices:

Example

/* For width smaller than 400px: */
body {
  background-image: url('img_smallflower.jpg');
}

/* For width 400px and larger: */
@media only screen and (min-width: 400px) {
  body {
    background-image: url('img_flowers.jpg');
  }
}

You can use the media query min-device-width, instead of min-width, which checks the device width, instead of the browser width. Then the image will not change when you resize the browser window:

Example

/* For devices smaller than 400px: */
body {
  background-image: url('img_smallflower.jpg');
}

/* For devices 400px and larger: */
@media only screen and (min-device-width: 400px) {
  body {
    background-image: url('img_flowers.jpg');
  }
}

The HTML Element

The HTML element gives web developers more flexibility in specifying image resources.

The most common use of the element will be for images used in responsive designs. Instead of having one image that is scaled up or down based on the viewport width, multiple images can be designed to more nicely fill the browser viewport.

The element works similar to the and elements. You set up different sources, and the first source that fits the preferences is the one being used:

Example


 
 
  Flowers

The srcset attribute is required, and defines the source of the image.

The media attribute is optional, and accepts the media queries you find in .

You should also define an element for browsers that do not support the element.

 

 
RWD Images

Responsive Web Design - Videos

 

Using The width Property

If the width property is set to 100%, the video player will be responsive and scale up and down:

Example

video {
  width: 100%;
  height: auto;
}

Notice that in the example above, the video player can be scaled up to be larger than its original size. A better solution, in many cases, will be to use the max-width property instead.


Using The max-width Property

If the max-width property is set to 100%, the video player will scale down if it has to, but never scale up to be larger than its original size:

Example

video {
  max-width: 100%;
  height: auto;
}

Add a Video to the Example Web Page

We want to add a video in our example web page. The video will be resized to always take up all the available space:

Example

video {
  width: 100%;
  height: auto;
}

 

 
RWD Videos

Responsive Web Design - Frameworks

 

There are many free CSS Frameworks that offer Responsive Design.


Using W3.CSS

A great way to create a responsive design, is to use a responsive style sheet, like

W3.CSS makes it easy to develop sites that look nice at any size!

Resize the page to see the responsiveness!

London

London is the capital city of England.

It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.

Paris

Paris is the capital of France.

The Paris area is one of the largest population centers in Europe, with more than 12 million inhabitants.

Tokyo

Tokyo is the capital of Japan.

It is the center of the Greater Tokyo Area, and the most populous metropolitan area in the world.

Example








 

W3Schools Demo


 

Resize this responsive page!




 

   

London


   

London is the capital city of England.


   

It is the most populous city in the United Kingdom,
    with a metropolitan area of over 13 million inhabitants.


 


 

   

Paris


   

Paris is the capital of France.


   

The Paris area is one of the largest population centers in Europe,
    with more than 12 million inhabitants.


 


 

   

Tokyo


   

Tokyo is the capital of Japan.


   

It is the center of the Greater Tokyo Area,
    and the most populous metropolitan area in the world.


 



To learn more about W3.CSS, read our .



Bootstrap

Another popular framework is Bootstrap. It uses HTML and CSS to make responsive web pages:

Example













 

My First Bootstrap Page


 

Resize this responsive page to see the effect!




 

   

     

Column 1


     

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


     

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...


   

   

     

Column 2


     

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


     

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...


   

   

     

Column 3


     

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


     

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...


   

 



To learn more about Bootstrap, go to our .

Ever heard about W3Schools Spaces? Here you can create your website from scratch or use a template, and host it for free.

* no credit card required

 

 
RWD Frameworks

Responsive Web Design - Templates


W3.CSS Web Site Templates

We have created some responsive templates with the .

You are free to modify, save, share, and use them in all your projects.

Tip: All templates below can be hosted for free with .


Band Template


Art Template


Architect Template


Coming Soon Template




Blog Template


Food Blog Template


Fashion Blog Template


Gourmet Catering Template


CV Template


Wedding Invitation Template


Photo Template


Black & White Photo Template


Photo III Template


Nature Portfolio Template


People Portfolio Template


People Portfolio II Template


Dark Portfolio Template


Black & White Portfolio Template


Parallax Template


Clothing Store Template


Interior Design Template


Cafe Template


Pizza Restaurant Template


Modal Restaurant Template


Start Page Template


Startup Template


App Launch Template


Marketing Template


Marketing / Website Template


Web Page Template


Social Media Template


Analytics Template


Apartment Rental Template


Hotel Template


Travel Template


Travel Agency Template


House Design Template


Screen 50/50 Template


Mail Template


Kitchen Sink/Demo Template



CSS Grid Layout Module


Header

Menu

Main

Right

Footer


Grid Layout

The CSS Grid Layout Module offers a grid-based layout system, with rows and columns, making it easier to design web pages without having to use floats and positioning.


Browser Support

The grid properties are supported in all modern browsers.

57.0 16.0 52.0 10 44

Grid Elements

A grid layout consists of a parent element, with one or more child elements.

Example

<div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">5</div>
  <div class="grid-item">6</div>
  <div class="grid-item">7</div>
  <div class="grid-item">8</div>
  <div class="grid-item">9</div>
</div>

1

2

3

4

5

6

7

8

9



Display Property

An HTML element becomes a grid container when its display property is set to grid or inline-grid.

Example

.grid-container {
  display: grid;
}

Example

.grid-container {
  display: inline-grid;
}

All direct children of the grid container automatically become grid items.


Grid Columns

The vertical lines of grid items are called columns.


Grid Rows

The horizontal lines of grid items are called rows.


Grid Gaps

The spaces between each column/row are called gaps.

You can adjust the gap size by using one of the following properties:

  • column-gap
  • row-gap
  • gap

Example

The column-gap property sets the gap between the columns:

.grid-container {
  display: grid;
  column-gap: 50px;
}

Example

The row-gap property sets the gap between the rows:

.grid-container {
  display: grid;
  row-gap: 50px;
}

Example

The gap property is a shorthand property for the row-gap and the column-gap properties:

.grid-container {
  display: grid;
  gap: 50px 100px;
}

Example

The gap property can also be used to set both the row gap and the column gap in one value:

.grid-container {
  display: grid;
  gap: 50px;
}


Grid Lines

The lines between columns are called column lines.

The lines between rows are called row lines.

Refer to line numbers when placing a grid item in a grid container:

Example

Place a grid item at column line 1, and let it end on column line 3:

.item1 {
  grid-column-start: 1;
  grid-column-end: 3;
}

Example

Place a grid item at row line 1, and let it end on row line 3:

.item1 {
  grid-row-start: 1;
  grid-row-end: 3;
}


All CSS Grid Properties

Property Description
Specifies the gap between the columns
A shorthand property for the row-gap and the column-gap properties
A shorthand property for the grid-template-rows, grid-template-columns, grid-template-areas, grid-auto-rows, grid-auto-columns, and the grid-auto-flow properties
Either specifies a name for the grid item, or this property is a shorthand property for the grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties
Specifies a default column size
Specifies how auto-placed items are inserted in the grid
Specifies a default row size
A shorthand property for the grid-column-start and the grid-column-end properties
Specifies where to end the grid item
Specifies the size of the gap between columns
Specifies where to start the grid item
A shorthand property for the grid-row-gap and grid-column-gap properties
A shorthand property for the grid-row-start and the grid-row-end properties
Specifies where to end the grid item
Specifies the size of the gap between rows
Specifies where to start the grid item
A shorthand property for the grid-template-rows, grid-template-columns and grid-areas properties
Specifies how to display columns and rows, using named grid items
Specifies the size of the columns, and how many columns in a grid layout
Specifies the size of the rows in a grid layout
Specifies the gap between the grid rows

CSS Grid Container


2

3

4

5

6

7

8


Grid Container

To make an HTML element behave as a grid container, you have to set the display property to grid or inline-grid.

Grid containers consist of grid items, placed inside columns and rows.


The grid-template-columns Property

The grid-template-columns property defines the number of columns in your grid layout, and it can define the width of each column.

The value is a space-separated-list, where each value defines the width of the respective column.

If you want your grid layout to contain 4 columns, specify the width of the 4 columns, or "auto" if all columns should have the same width.

Example

Make a grid with 4 columns:

.grid-container {
  display: grid;
  grid-template-columns: auto auto auto auto;
}

Note: If you have more than 4 items in a 4 columns grid, the grid will automatically add a new row to put the items in.

The grid-template-columns property can also be used to specify the size (width) of the columns.

Example

Set a size for the 4 columns:

.grid-container {
  display: grid;
  grid-template-columns: 80px 200px auto 40px;
}


The grid-template-rows Property

The grid-template-rows property defines the height of each row.

1

2

3

4

5

6

7

8

The value is a space-separated-list, where each value defines the height of the respective row:

Example

.grid-container {
  display: grid;
  grid-template-rows: 80px 200px;
}



The justify-content Property

The justify-content property is used to align the whole grid inside the container.

1

2

3

4

5

6

Note: The grid's total width has to be less than the container's width for the justify-content property to have any effect.

Example

.grid-container {
  display: grid;
  justify-content: space-evenly;
}

Example

.grid-container {
  display: grid;
  justify-content: space-around;
}

Example

.grid-container {
  display: grid;
  justify-content: space-between;
}

Example

.grid-container {
  display: grid;
  justify-content: center;
}

Example

.grid-container {
  display: grid;
  justify-content: start;
}

Example

.grid-container {
  display: grid;
  justify-content: end;
}


The align-content Property

The align-content property is used to vertically align the whole grid inside the container.

1

2

3

4

5

6

Note: The grid's total height has to be less than the container's height for the align-content property to have any effect.

Example

.grid-container {
  display: grid;
  height: 400px;
  align-content: center;
}

Example

.grid-container {
  display: grid;
  height: 400px;
  align-content: space-evenly;
}

Example

.grid-container {
  display: grid;
  height: 400px;
  align-content: space-around;
}

Example

.grid-container {
  display: grid;
  height: 400px;
  align-content: space-between;
}

Example

.grid-container {
  display: grid;
  height: 400px;
  align-content: start;
}

Example

.grid-container {
  display: grid;
  height: 400px;
  align-content: end;
}


CSS Grid Item


2

3

4

5


Child Elements (Items)

A grid container contains grid items.

By default, a container has one grid item for each column, in each row, but you can style the grid items so that they will span multiple columns and/or rows.


The grid-column Property:

The grid-column property defines on which column(s) to place an item.

You define where the item will start, and where the item will end.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

Note: The grid-column property is a shorthand property for the grid-column-start and the grid-column-end properties.

To place an item, you can refer to line numbers, or use the keyword "span" to define how many columns the item will span.

Example

Make "item1" start on column 1 and end before column 5:

.item1 {
  grid-column: 1 / 5;
}

Example

Make "item1" start on column 1 and span 3 columns:

.item1 {
  grid-column: 1 / span 3;
}

Example

Make "item2" start on column 2 and span 3 columns:

.item2 {
  grid-column: 2 / span 3;
}


The grid-row Property:

The grid-row property defines on which row to place an item.

You define where the item will start, and where the item will end.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Note: The grid-row property is a shorthand property for the grid-row-start and the grid-row-end properties.

To place an item, you can refer to line numbers, or use the keyword "span" to define how many rows the item will span:

Example

Make "item1" start on row-line 1 and end on row-line 4:

.item1 {
  grid-row: 1 / 4;
}

Example

Make "item1" start on row 1 and span 2 rows:

.item1 {
  grid-row: 1 / span 2;
}



The grid-area Property

The grid-area property can be used as a shorthand property for the grid-row-start, grid-column-start, grid-row-end and the grid-column-end properties.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

Example

Make "item8" start on row-line 1 and column-line 2, and end on row-line 5 and column line 6:

.item8 {
  grid-area: 1 / 2 / 5 / 6;
}

Example

Make "item8" start on row-line 2 and column-line 1, and span 2 rows and 3 columns:

.item8 {
  grid-area: 2 / 1 / span 2 / span 3;
}

Naming Grid Items

The grid-area property can also be used to assign names to grid items.

Header

Menu

Main

Right

Footer

Named grid items can be referred to by the grid-template-areas property of the grid container.

Example

Item1 gets the name "myArea" and spans all five columns in a five columns grid layout:

.item1 {
  grid-area: myArea;
}
.grid-container {
  grid-template-areas: 'myArea myArea myArea myArea myArea';
}

Each row is defined by apostrophes (' ')

The columns in each row is defined inside the apostrophes, separated by a space.

Note: A period sign represents a grid item with no name.

Example

Let "myArea" span two columns in a five columns grid layout (period signs represent items with no name):

.item1 {
  grid-area: myArea;
}
.grid-container {
  grid-template-areas: 'myArea myArea . . .';
}

To define two rows, define the column of the second row inside another set of apostrophes:

Example

Make "item1" span two columns and two rows:

.grid-container {
  grid-template-areas: 'myArea myArea . . .' 'myArea myArea . . .';
}

Example

Name all items, and make a ready-to-use webpage template:

.item1 { grid-area: header; }
.item2 { grid-area: menu; }
.item3 { grid-area: main; }
.item4 { grid-area: right; }
.item5 { grid-area: footer; }

.grid-container {
  grid-template-areas:
    'header header header header header header'
    'menu main main main right right'
    'menu footer footer footer footer footer';
}


The Order of the Items

The Grid Layout allows us to position the items anywhere we like.

The first item in the HTML code does not have to appear as the first item in the grid.

1

2

3

4

5

6

Example

.item1 { grid-area: 1 / 3 / 2 / 4; }
.item2 { grid-area: 2 / 3 / 3 / 4; }
.item3 { grid-area: 1 / 1 / 2 / 2; }
.item4 { grid-area: 1 / 2 / 2 / 3; }
.item5 { grid-area: 2 / 1 / 3 / 2; }
.item6 { grid-area: 2 / 2 / 3 / 3; }

You can re-arrange the order for certain screen sizes, by using media queries:

Example

@media only screen and (max-width: 500px) {
  .item1 { grid-area: 1 / span 3 / 2 / 4; }
  .item2 { grid-area: 3 / 3 / 4 / 4; }
  .item3 { grid-area: 2 / 1 / 3 / 2; }
  .item4 { grid-area: 2 / 2 / span 2 / 3; }
  .item5 { grid-area: 3 / 1 / 4 / 2; }
  .item6 { grid-area: 2 / 3 / 3 / 4; }
}


CSS Templates


CSS Layout Templates

We have created some responsive starter templates with CSS.

You are free to modify, save, share, and use them in all your projects.

Header, equal columns and footer:

Header, unequal columns and footer:

Topnav, content and footer:

Sidenav and content:

Ever heard about W3Schools Spaces? Here you can create your website from scratch or use a template, and host it for free.

* no credit card required


CSS Examples


CSS Syntax


CSS Selectors


CSS How To / Where To


CSS Comments


CSS Colors


CSS Backgrounds


CSS Borders


CSS Margins



CSS Padding


CSS Height/Width


CSS Box Model


CSS Outline


CSS Text


CSS Fonts


CSS Icons


CSS Links


CSS Lists


CSS Tables


CSS Display


CSS Positioning


CSS Overflow


CSS Floating


CSS Inline-block


CSS Aligning Elements


CSS Combinators


CSS Pseudo-classes


CSS Pseudo-elements


CSS Opacity


CSS Navigation Bars


CSS Dropdowns


CSS Image Gallery


CSS Image Sprites


CSS Attribute Selectors


CSS Forms


CSS Counters


CSS Website Layout


CSS Rounded Corners


CSS Border Images


CSS Backgrounds


CSS Gradients


CSS Shadow Effects


CSS Text Effects


CSS Web Fonts


CSS 2D Transforms


CSS 3D Transforms


CSS Transitions


CSS Animations


CSS Tooltips


CSS Style Images


CSS Image Reflection


CSS Object-fit


CSS Object-position


CSS Buttons


CSS Pagination


CSS Multiple Columns


CSS User Interface


CSS Variables


CSS Box Sizing


CSS Flexbox


CSS Media Queries


CSS Media Queries - More Examples


CSS Responsive Webdesign


CSS Grid


CSS Online Editor


CSS Editor

With our online CSS editor, you can edit HTML, CSS and JavaScript code, and view the result in your browser.


Size:

Example

body {
  background-color: lightblue;
}

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

p {
  font-family: verdana;
}

My First CSS Example

This is a paragraph.

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


Publish Your Code

If you want to save your HTML, CSS and JavaScript code, and create your own website, check out .

is a website-building tool that lets you make and share your own website.

You can change the website's look and how it works by editing the code right in your web browser.

It's easy to use and doesn't require any setup:

The code editor is packed with features to help you achieve more:

  • Templates: Start from scratch or use a template
  • Cloud-based: no installations required. You only need your browser
  • Terminal & Log: debug and troubleshoot your code easily
  • File Navigator: switch between files inside the code editor
  • And much more!

Learn Faster

Practice is key to mastering coding, and the best way to put your CSS knowledge into practice is by getting practical with code.

Use to build, test and deploy code.

The code editor lets you write and practice different types of computer languages. It includes HTML/CSS/JavaScript, but you can use it for other languages too, such as PHP, Python, Node.js, etc.

If you don't know CSS, we suggest that you read our from scratch.


Build Powerful Websites

You can also use the code editor in to build frontend or full-stack websites from scratch.

Or you can use the 60+ templates available and save time:

Photographer website template
Blog website template
Webshop template
Tutor website template

Create your Spaces account today and explore them all!


Share It With The World

Host and publish your websites in no time with .

W3Schools subdomain and SSL certificate are included for free with . An SSL certificate makes your website safe and secure. It also helps people trust your website and makes it easier to find it online.

Want a custom domain for your website?

You can buy a domain or transfer an existing one and connect it to your space.


How Does It Work?

Get started in a few clicks with .


CSS Snippets


CSS Snippets

Have you ever seen a cool feature on a website and thought "How do they do that"?

We have collected a bunch of CSS snippets that you can use in your projects, for free:

Nature
Nature
Beautiful sunrise








How To - Snippets Library

For more snippets, you can visit our , that include hundreds of code snippets for HTML, CSS and JavaScript.


CSS Quiz


You can test your CSS skills with W3Schools' Quiz.


The Test

The test contains 25 questions and there is no time limit. 

The test is not official, it's just a nice way to see how much you know, or don't know, about CSS.

Count Your Score

You will get 1 point for each correct answer. At the end of the Quiz, your total score will be displayed. Maximum score is 25 points.

Start the Quiz

Good luck!

If you don't know CSS, we suggest that you read our from scratch.


Kickstart your career

Get certified by completing the course

w3schools CERTIFIED . 2023

CSS Exercises


You can test your CSS skills with W3Schools' Exercises.


Exercises

We have gathered a variety of CSS exercises (with answers) for each CSS Chapter.

Try to solve an exercise by editing some code. Get a "hint" if you're stuck, or show the answer to see what you've done wrong.

Count Your Score

You will get 1 point for each correct answer. Your score and total score will always be displayed.

Start CSS Exercises

Good luck!

If you don't know CSS, we suggest that you read our from scratch.


Kickstart your career

Get certified by completing the course

w3schools CERTIFIED . 2023

W3Schools CSS Bootcamp

 

HTML & CSS Bootcamp

Learn with W3Schools.

Live online learning sessions.

Duration: 3 Weeks.

 

w3schools BOOTCAMP . 2023

In this mini bootcamp, you will learn the foundational skills needed to create beautiful and functional websites, from writing HTML markup to styling your pages with CSS.

You will learn HTML and CSS over a 3 weeks period together with a live instructor and an interactive cohort of engaged learners!

You Will Learn
  • HTML and CSS fundamentals including Elements, Attributes, Tables, Forms and more.
  • How to write best fit Semantic HTML
  • How to create your first functional website utilising HTML & CSS standards
  • How to structure websites logically and ensure they are correctly formatted for accessibility
  • The basics of website design and styling using CSS for layout, positioning, grid and responsive design
  • CSS Flexbox for positioning and layout
  • How to implement functional forms, lists, tables and media on a website
  • How to control the style and layout of multiple web pages all at once
  • How to change the appearance and layout of all the pages in a Web site

3 Reasons to Join the Bootcamp

1. Live Online Instruction

Learn directly from experienced instructors through live online learning sessions.

2. Live Sessions

Learn three evenings per week between 7pm and 9pm, available in multiple time zones.

3. Affordable & Flexible

One of the most affordable instructor-led online bootcamps, with flexible payment options.

 

How it Works

1. Application and Enrollment:
Reserve your seat and enroll in the bootcamp by paying the bootcamp fee of only $395. The price includes the exam fee and 18 hours with live instructor.

2. Complete the Bootcamp:
After enrollment, you will be placed in a learning cohort with other students. You will go through the course material together and complete assignments and projects with the help of an experienced instructor.

By the end of this bootcamp you will learn HTML and CSS. The curriculum used is the and . The bootcamp will help you prepare for the W3Schools HTML and CSS exam so that you can document and validate your competence by getting certified.

Throughout the bootcamp, you will receive support from your cohort and the W3Schools team to help you grow your skill set.

3. Certification and Job Application:
Upon completing the bootcamp, you will have passed the W3Schools HTML and CSS exams and obtained the Certified HTML Developer and Certified CSS Developer titles and an extra acknowledgement that you were a part of the bootcamp on the certification. This certification demonstrates that you know HTML and CSS.

 



 
CSS Bootcamp

W3Schools CSS Certificate

 

w3schools CERTIFIED . 2023   

W3Schools offers an Online Certification Program.

The perfect solution for busy professionals who need to balance work, family, and career building.

More than 50 000 certificates already issued!


 

w3schools CERTIFIED . 2023

W3Schools offers an Online Certification Program.

The perfect solution for busy professionals who need to balance work, family, and career building.

More than 50 000 certificates already issued!

 

Document your skills
Improve your career
Study at your own pace
Save time and money
Known brand
Trusted by top companies

Who Should Consider Getting Certified?

Any student or professional within the digital industry.

Certifications are valuable assets to gain trust and demonstrate knowledge to your clients, current or future employers on a ever increasing competitive market.

W3Schools is Trusted by Top Companies

W3Schools has over two decades of experience with teaching coding online.

Our certificates are recognized and valued by companies looking to employ skilled developers.

Save Time and Money

Show the world your coding skills by getting a certification.

The prices is a small fraction compared to the price of traditional education.

Document and validate your competence by getting certified!

Exam overview

Fee: 95 USD

Number of questions: 70

Requirement to pass: 75% correct answers

Time limit: 70 minutes

Number of attempts to pass: Two

Exam deadline: None

Certification Expiration: None

Format: Online, multiple choice

 


Advance Faster in Your Career

Getting a certificate proves your commitment to upgrading your skills.

The certificate can be added as credentials to your CV, Resume, LinkedIn profile, and so on.

It gives you the credibility needed for more responsibilities, larger projects, and a higher salary.

Knowledge is power, especially in the current job market.

Documentation of your skills enables you to advance your career or helps you to start a new one.


How Does It Work?

  • Study for free at W3Schools.com
  • Study at your own speed
  • Test your skills with W3Schools online quizzes
  • Apply for your certificate by paying an exam fee
  • Take your exam online, at any time, and from any location

Get Your Certificate and Share It With The World

Example certificate:

Each certificate gets a unique link that can be shared with others.

Validate your certification with the link or QR code.

Check how it looks like in this .

Share your certificate on LinkedIn in the Certifications section in just one click!


Document Your Skills

Getting a certificate proves your commitment to upgrade your skills, gives you the credibility needed for more responsibilities, larger projects, and a higher salary.


 


Looking to add multiple users?

Are you an educator, manager or business owner looking for courses or certifications?

We are working with schools, companies and organizations from all over the world.

 


 
CSS Certificate

Login
ADS CODE