Você está na página 1de 332

CSS Tutorial

W3Schools Home

Next Chapter
CSS

CSS is a stylesheet language that describes the presentation of an HTML (or


XML) document.
CSS describes how elements must be rendered on screen, on paper, or in
other media.
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: #d0e4fe;
}
h1 {
color: orange;
text-align: center;
}
p{

font-family: "Times New Roman";


font-size: 20px;
}
Try it Yourself
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.
Try-It-Yourself!

CSS Quiz Test


Test your CSS skills at W3Schools!
Start CSS Quiz!

CSS References
At W3Schools you will find complete CSS references of all properties and
selectors with syntax, examples, browser support, and more.
CSS Properties Reference
CSS Selectors Reference
CSS Aural Reference
CSS Units

CSS Color Reference

Exam - Get Your Diploma!

W3Schools' Online Certification


The perfect solution for professionals who need to balance work, family, and
career building.
More than 10 000 certificates already issued!
Get Your Certificate
The HTML Certificate documents your knowledge of HTML.
The HTML5 Certificate documents your knowledge of advanced HTML5.
The CSS Certificate documents your knowledge of advanced CSS.
The JavaScript Certificate documents your knowledge of JavaScript and HTML
DOM.
The jQuery Certificate documents your knowledge of jQuery.
The PHP Certificate documents your knowledge of PHP and SQL (MySQL).
The XML Certificate documents your knowledge of XML, XML DOM and XSLT.
The Bootstrap Certificate documents your knowledge of the Bootstrap
framework.

W3Schools Home
Next Chapter

W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:
Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring

SHARE THIS PAGE

CSS Introduction
Previous
Next Chapter

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 Solved a Big Problem


HTML was NEVER intended to contain tags for formatting a web page!
HTML was created to describe the content of a web page, like:
<h1>This is a heading</h1>

<p>This is a paragraph.</p>
When tags like <font>, and color attributes were added to the HTML 3.2
specification, it started a nightmare for web developers. Development of large
websites, where fonts and color information were added to every single page,
became a long and expensive process.
To solve this problem, the World Wide Web Consortium (W3C) created CSS.
CSS removed the style formatting from the HTML page!

CSS Saves a Lot of Work!


The style definitions are normally saved in external .css files.
With an external stylesheet file, you can change the look of an entire website by
changing just one file!

CSS Syntax and Selectors


Previous
Next Chapter

CSS Syntax
A CSS rule-set consists of a selector and a declaration block:

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.
A CSS declaration always ends with a semicolon, and declaration blocks are
surrounded by curly braces.
In the following example all <p> elements will be center-aligned, with a red
text color:

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

Try it Yourself

CSS Selectors
CSS selectors are used to "find" (or select) HTML elements based on their
element name, id, class, attribute, and more.

The element Selector


The element selector selects elements based on the element name.
You can select all <p> elements on a page like this (in this case, all <p>
elements will be center-aligned, with a red text color):

Example

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

Try it Yourself

The id Selector
The id selector uses the id attribute of an HTML element to select a specific
element.
The id of an element should be 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.
The style rule below will be applied to the HTML element with id="para1":

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

Try it Yourself

Note: An id name cannot start with a number!

The class Selector


The class selector selects elements with a specific class attribute.

To select elements with a specific class, write a period (.) character, followed by
the name of the class.
In the example below, all HTML elements with class="center" will be red and
center-aligned:

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

Try it Yourself
You can also specify that only specific HTML elements should be affected by a
class.
In the example below, only <p> elements with class="center" will be centeraligned:

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

Try it Yourself
HTML elements can also refer to more than one class.
In the example below, the <p> element will be styled according to
class="center" and to class="large":

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

Try it Yourself

Note: A class name cannot start with a number!

Grouping Selectors
If you have elements with the same style definitions, like this:
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.
In the example below we have grouped the selectors from the code above:

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

Try it Yourself

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 starts with /* and ends with */. Comments can also span
multiple lines:

Example
p{
color: red;
/* This is a single-line comment */
text-align: center;
}
/* This is
a multi-line
comment */

Try it Yourself

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4

CSS How To...


Previous
Next Chapter

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 style sheet

Internal style sheet

Inline style

External Style Sheet


With an external style sheet, you can change the look of an entire website by
changing just one file!
Each page must include a reference to the external style sheet file inside the
<link> element. The <link> element goes inside the <head> section:

Example
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
Try it Yourself
An external style sheet can be written in any text editor. The file should not
contain any html tags. The style sheet file must be saved with a .css extension.
Here is how the "myStyle.css" looks:

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

Do not add a space between the property value and the unit (such as margin-left:20 p
correct way is: margin-left:20px;

Internal Style Sheet


An internal style sheet may be used if one single page has a unique style.
Internal styles are defined within the <style> element, inside the <head>
section of an HTML page:

Example
<head>
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
Try it Yourself

Inline Styles
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.

The example below shows how to change the color and the left margin of a
<h1> element:

Example
<h1 style="color:blue;margin-left:30px;">This is a heading.</h1>
Try it Yourself

An inline style loses many of the advantages of a style sheet (by mixing content with p
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.

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

h1 {
color: navy;
}
then, assume that an internal style sheet also has the following style for the
<h1> element:

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

Example

<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<style>
h1 {
color: orange;
}
</style>
</head>
Try it Yourself
However, if the internal style is defined before the link to the external style
sheet, the <h1> elements will be "navy":

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

Cascading Order
What style will be used when there is more than one style specified for an HTML
element?
Generally speaking we can say that all the styles 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 (inside a specific HTML element) has the highest priority,
which means that it will override a style defined inside the <head> tag, or in an
external style sheet, or a browser default value.
Try it Yourself

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4

CSS Colors
Previous
Next Chapter

Colors are displayed combining RED, GREEN, and BLUE light.

Colors in CSS are most often specified by:

a valid color name - like "red"

an RGB value - like "rgb(255, 0, 0)"

a HEX value - like "#ff0000"

Color Names
Colors set by using color names:

Example

Color

Name

Red

Green

Blue

Orange

Yellow

Cyan

Black
Try it Yourself
Note: Color names are case-insensitive: "Red" is the same as "red" or "RED".
HTML and CSS supports 140 standard color names.

RGB (Red, Green, Blue)


RGB color values can be specified using this formula: rgb(red, green, blue).
Each parameter (red, green, 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. Experiment by mixing the RGB values below:

Red

Green

Blue

255

rgb(255, 0, 0)

Example
Color

RGB

rgb(255,0,0)

rgb(0,255,0)

rgb(0,0,255)

rgb(255,165,0)

rgb(255,255,0)

rgb(0,255,255)
Try it Yourself
Shades of grey are often defined using equal values for all the 3 light sources:

Example
Color

RGB

rgb(0,0,0)

rgb(128,128,128)

rgb(255,255,255)
Try it Yourself

Hexadecimal Colors
RGB values can also be specified using hexadecimal color values 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). Note: HEX values are case-insensitive: "#ff0000" is the
same as "FF0000".

Example
Color

HEX

#FF0000

#00FF00

#0000FF

#FFA500

#FFFF00

#00FFFF
Try it Yourself
Shades of grey are often defined using equal values for all the 3 light sources:

Example
Color

HEX

#000000

#808080

#FFFFFF
Try it Yourself

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:
Color Converter
Google Maps

Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring

SHARE THIS PAGE

CSS Backgrounds
Previous
Next Chapter
The CSS background properties are used to define the background effects
for elements.
CSS background properties:

background-color

background-image

background-repeat

background-attachment

background-position

Background Color

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


The background color of a page is set like this:

Example
body {
background-color: lightblue;
}
Try it Yourself
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 CSS Color Values for a complete list of possible color values.
In the example below, the <h1>, <p>, and <div> elements have different background colors:

Example
h1 {
background-color: green;
}
div {
background-color: lightblue;
}
p{
background-color: yellow;
}
Try it Yourself

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.


The background image for a page can be set like this:

Example
body {
background-image: url("paper.gif");
}
Try it Yourself
Below is an example of a bad combination of text and background image. The text is hardly
readable:

Example
body {
background-image: url("bgdesert.jpg");
}
Try it Yourself

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

Background Image - Repeat Horizontally


or Vertically
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");
}

Try it Yourself
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;
}
Try it Yourself

Note: To repeat an image vertically set background-repeat: repeat-y;

Background Image - Set position and norepeat


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

Example
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
}
Try it Yourself
In the example above, the background image is shown 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.
The position of the image is specified by the background-position property:

Example

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

Background Image - Fixed position


To specify that the background image should be fixed (will not scroll with the rest of the page),
use thebackground-attachment property:

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

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.
The shorthand property for background is background:

Example
body {
background: #ffffff url("img_tree.png") no-repeat right top;
}
Try it Yourself
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.

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4 Exercise 5

All CSS Background Properties


Property

Description

background

Sets all the background properties in one declaration

background-attachment

Sets whether a background image is fixed or scrolls with the rest of the p

background-color

Sets the background color of an element

background-image

Sets the background image for an element

background-position

Sets the starting position of a background image

background-repeat

Sets how a background image will be repeated

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:
Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring

SHARE THIS PAGE

CSS Borders

Previous
Next Chapter

CSS Border Properties


The CSS border properties allow you to specify the style, width, and color of an
element's border.
This element has a groove border that is 15px wide and green.

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 bordercolor value

ridge - Defines a 3D ridged border. The effect depends on the bordercolor 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 bordercolor 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
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.
Try it Yourself

Note: None of the OTHER CSS border properties described below will have ANY effect
theborder-style property is set!

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.
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;
}
p.two {
border-style: solid;
border-width: medium;
}
p.three {
border-style: solid;
border-width: 2px 10px 4px 20px;
}
Try it Yourself

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

transparent

The border-color property can have from one to four values (for the top
border, right border, bottom border, and the left border).
If border-color is not set, it inherits the color of the element.

Example
p.one {
border-style: solid;
border-color: red;
}
p.two {
border-style: solid;
border-color: green;
}
p.three {
border-style: solid;
border-color: red green blue yellow;
}
Try it Yourself

Border - Individual Sides

From the examples above you have seen that it is possible to specify a different
border for each side.
In CSS, there is 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;
}
Try it Yourself
The example above gives the same result as this:

Example
p{
border-style: dotted solid;
}
Try it Yourself
So, here is how it works:
If the border-style property has four values:

border-style: dotted solid double dashed;


o top border is dotted
o right border is solid
o bottom border is double
o left border is dashed

If the border-style property has three values:

border-style: dotted solid double;


o top border is dotted
o right and left borders are solid
o bottom border is double

If the border-style property has two values:

border-style: dotted solid;


o top and bottom borders are dotted
o right and left borders are solid

If the border-style property has one value:

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

The border-style property is used in the example above. However, it also


works with border-width andborder-color.

Border - Shorthand Property


As you can see from the examples above, 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;
}
Try it Yourself

More Examples
All the top border properties in one declaration
This example demonstrates a shorthand property for setting all of the properties
for the top border in one declaration.
Set the style of the bottom border
This example demonstrates how to set the style of the bottom border.
Set the width of the left border
This example demonstrates how to set the width of the left border.
Set the color of the four borders
This example demonstrates how to set the color of the four borders. It can have
from one to four colors.
Set the color of the right border
This example demonstrates how to set the color of the right border.

Test Yourself with Exercises!

Exercise 1 Exercise 2 Exercise 3 Exercise 4

All CSS Border Properties


Property

Description

border

Sets all the border properties in one declaration

border-bottom

Sets all the bottom border properties in one declaration

border-bottom-color

Sets the color of the bottom border

border-bottom-style

Sets the style of the bottom border

border-bottom-width

Sets the width of the bottom border

border-color

Sets the color of the four borders

border-left

Sets all the left border properties in one declaration

border-left-color

Sets the color of the left border

border-left-style

Sets the style of the left border

border-left-width

Sets the width of the left border

border-right

Sets all the right border properties in one declaration

border-right-color

Sets the color of the right border

border-right-style

Sets the style of the right border

border-right-width

Sets the width of the right border

border-style

Sets the style of the four borders

border-top

Sets all the top border properties in one declaration

border-top-color

Sets the color of the top border

border-top-style

Sets the style of the top border

border-top-width

Sets the width of the top border

border-width

Sets the width of the four borders

CSS Margins
Previous

Next Chapter

CSS Margin Properties


The CSS margin properties are used to generate space around elements.
The margin properties set the size of the white space OUTSIDE the border.
This element has a margin of 80px.

CSS Margins
The CSS margin properties set the size of the white space OUTSIDE the border.

Note: The margins are completely transparent - and cannot have a background color!

With CSS, you have full control over the margins. There are CSS 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

Note: It is also possible to use negative values for margins; to overlap content.

The following example sets different margins for all four sides of a <p>
element:

Example
p{
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 80px;
}
Try it Yourself
The following example lets the left margin be inherited from the parent
element:

Example
div.container {
border: 1px solid red;
margin-left: 100px;
}
p.one {
margin-left: inherit;
}

Try it Yourself

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

Example
p{
margin: 100px 150px 100px 80px;
}
Try it Yourself
So, here is how it works:
If the margin property has four values:

margin: 25px 50px 75px 100px;


o top margin is 25px
o right margin is 50px
o bottom margin is 75px
o left margin is 100px

If the margin property has three values:

margin: 25px 50px 75px;


o top margin is 25px
o right and left margins are 50px
o bottom margin is 75px

If the margin property has two values:

margin: 25px 50px;


o top and bottom margins are 25px
o right and left margins are 50px

If the margin property has one value:

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

Use of 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
div {
width: 300px;
margin: auto;
border: 1px solid red;
}

Try it Yourself

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4

All CSS Margin Properties


Property

Description

margin

A shorthand property for setting the margin properties in one declaratio

margin-bottom

Sets the bottom margin of an element

margin-left

Sets the left margin of an element

margin-right

Sets the right margin of an element

margin-top

Sets the top margin of an element

Previous
Next Chapter

CSS Padding
Previous

Next Chapter

CSS Padding Properties


The CSS padding properties are used to generate space around content.
The padding properties set the size of the white space between the element
content and the element border.
This element has a padding of 50px.

CSS Padding
The CSS padding properties define the white space between the element
content and the element border.
The padding clears an area around the content (inside the border) of an
element.

Note: The padding is affected by the background color of the element!

With CSS, you have full control over the padding. There are CSS 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

The following example sets different padding for all four sides of a <p>
element:

Example
p{
padding-top: 50px;
padding-right: 30px;
padding-bottom: 50px;
padding-left: 80px;
}
Try it Yourself

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

Example
p{
padding: 50px 30px 50px 80px;
}
Try it Yourself
So, here is how it works:
If the padding property has four values:

padding: 25px 50px 75px 100px;


o top padding is 25px
o right padding is 50px
o bottom padding is 75px
o left padding is 100px

If the padding property has three values:

padding: 25px 50px 75px;


o top padding is 25px
o right and left paddings are 50px
o bottom padding is 75px

If the padding property has two values:

padding: 25px 50px;


o top and bottom paddings are 25px

o right and left paddings are 50px


If the padding property has one value:

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

More Examples
All the padding properties in one declaration
This example demonstrates a shorthand property for setting all of the padding
properties in one declaration, can have from one to four values.
Set the left padding
This example demonstrates how to set the left padding of a <p> element.
Set the right padding
This example demonstrates how to set the right padding of a <p> element.
Set the top padding
This example demonstrates how to set the top padding of a <p> element.
Set the bottom padding
This example demonstrates how to set the bottom padding of a <p> element.

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3

All CSS Padding Properties


Property

Description

padding

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

padding-bottom

Sets the bottom padding of an element

padding-left

Sets the left padding of an element

padding-right

Sets the right padding of an element

padding-top

Sets the top padding of an element

CSS Height and Width Dimensions


Previous
Next Chapter

CSS Dimension Properties


The CSS dimension properties allow you to control the height and width of an element.
This element has a width of 100%.

Setting height and width


The height and width properties are used to set the height and width of an element.
The height and width can be set to auto (this is default. Means that the browser calculates the
height and width), or be specified in length values, like px, cm, etc., or in percent (%) of the
containing block.
This <div> element has a height of 100 pixels and a width of 500 pixels.

Note: 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!
The following example shows a <div> element with a height of 100 pixels and a width of 500
pixels:

Example
div {
width: 500px;
height: 100px;
border: 3px solid #73AD21;
}

Try it Yourself

Setting max-width
The max-width property is used to set the maximum width of an element.
The max-width can be specified in length values, like px, cm, etc., or in percent (%) of the
containing block, or set to none (this is default. Means that there is no maximum width).
The problem with the <div> above occurs when the browser window is smaller than the width of
the element (500px). The browser then adds a horizontal scrollbar to the page.
Using max-width instead, in this situation, will improve the browser's handling of small
windows.

Tip: Drag the browser window to smaller than 500px wide, to see the difference between the two
divs!
This <div> element has a height of 100 pixels and a max-width of 500 pixels.

Note: The value of the max-width property overrides width.


The following example shows a <div> element with a height of 100 pixels and a max-width of
500 pixels:

Example
div {
max-width: 500px;
height: 100px;
border: 3px solid #73AD21;
}

Try it Yourself

Try it Yourself - Examples


Set the height and width of elements
This example demonstrates how to set the height and width of different elements.
Set the height and width of an image using percent
This example demonstrates how to set the height and width of an image using a percent value.
Set min-width and max-width of an element
This example demonstrates how to set a minimum width and a maximum width of an element
using a pixel value.
Set min-height and max-height of an element
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 1 Exercise 2

All CSS Dimension Properties


Property

Description

height

Sets the height of an element

max-height

Sets the maximum height of an element

max-width

Sets the maximum width of an element

min-height

Sets the minimum height of an element

min-width

Sets the minimum width of an element

width

Sets the width of an element

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications
COLOR PICKER

LEARN MORE:

Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring
SHARE THIS PAGE

CSS Text
Previous

Next Chapter

TEXT FORMATTING
This text is styled with some of the text formatting
properties.
The
heading
uses
the
text-align,
texttransform,
and
color
properties.
The
paragraph
is
indented, aligned, and the space between characters is
s p e c i f i e d . T h e u n d e r l i n e i s r e m o v e d f r o m t h i s c o l o r e d " Try
it Yourself" link.

Text Color
The color property is used to set the color of the text.
With CSS, a color is most often specified by:

a color name - like "red"

a HEX value - like "#ff0000"

an RGB value - like "rgb(255,0,0)"

Look at CSS Color Values 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;
}
Try it Yourself

Note: For W3C compliant CSS: If you define the color property, you must also define
thebackground-color property.

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;
}
Try it Yourself
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;
}
Try it Yourself

Text Decoration
The text-decoration property is used to set or remove decorations from text.
The value text-decoration: none; is often used to remove underlines from
links:

Example
a{
text-decoration: none;
}
Try it Yourself
The other text-decoration values are used to decorate text:

Example
h1 {
text-decoration: overline;
}
h2 {
text-decoration: line-through;
}
h3 {
text-decoration: underline;
}
Try it Yourself

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

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;
}
Try it Yourself

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

Example
p{
text-indent: 50px;
}
Try it Yourself

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

}
h2 {
letter-spacing: -3px;
}
Try it Yourself

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;
}
Try it Yourself

Text Direction
The direction property is used to change the text direction of an element:

Example
div {
direction: rtl;
}
Try it Yourself

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
h1 {
word-spacing: 10px;
}
h2 {
word-spacing: -5px;
}
Try it Yourself

More Examples
Disable text wrapping inside an element
This example demonstrates how to disable text wrapping inside an element.
Vertical alignment of an image
This example demonstrates how to set the vertical align of an image in a text.
Add shadow to text
This example demonstrates how to add shadow to text.

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4 Exercise 5

CSS Fonts
Previous

Next Chapter

The CSS font properties define the font family, boldness, size, and the style
of a text.

Difference Between Serif and Sans-serif


Fonts

CSS Font Families


In CSS, there are two types of font family names:

generic family - a group of font families with a similar look (like "Serif"
or "Monospace")

font family - a specific font family (like "Times New Roman" or "Arial")

Generic family

Font family

Description

Serif

Times New Roman


Georgia

Serif fonts have small lines at the ends


characters

Sans-serif

Arial
Verdana

"Sans" means without - these fonts do


lines at the ends of characters

Monospace

Courier New
Lucida Console

All monospace characters have the sam

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

Font Family
The font family of a text is set with the font-family property.
The font-family property should hold several font names as a "fallback"
system. If the browser does not support the first font, it tries the next font, and
so on.
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.
Note: If the name of a font family is more than one word, it must be in
quotation marks, like: "Times New Roman".
More than one font family is specified in a comma-separated list:

Example

p{
font-family: "Times New Roman", Times, serif;
}
Try it Yourself
For commonly used font combinations, look at our Web Safe Font Combinations.

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;
}
Try it Yourself

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 <h1> - <h6> for headings and <p> 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
(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;
}
Try it Yourself
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.
The em size unit is recommended by the W3C.
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 */
}

Try it Yourself
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 IE. 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 <body> element:

Example
body {
font-size: 100%;
}
h1 {
font-size: 2.5em;
}
h2 {
font-size: 1.875em;
}
p{
font-size: 0.875em;
}
Try it Yourself
Our code now works great! It shows the same text size in all browsers, and
allows all browsers to zoom or resize the text!

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

Example
p.normal {
font-weight: normal;
}
p.thick {
font-weight: bold;
}
Try it Yourself

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;
}
Try it Yourself

More Examples
All the font properties in one declaration
This example demonstrates how to use the shorthand property for setting all of
the font properties in one declaration.

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4 Exercise 5

All CSS Font Properties


Property

Description

font

Sets all the font properties in one declaration

font-family

Specifies the font family for text

font-size

Specifies the font size of text

font-style

Specifies the font style for text

font-variant

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

font-weight

Specifies the weight of a font

CSS Links
Previous
Next Chapter

With CSS, links can be styled in different ways.


Text Link Text Link

Link Button

Link Button

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

Example
a{
color: hotpink;
}
Try it Yourself
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;
}
Try it Yourself
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;
}
Try it Yourself

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;
}
Try it Yourself

Advanced - 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;
}
Try it Yourself

More Examples
Add different styles to hyperlinks
This example demonstrates how to add other styles to hyperlinks.
Advanced - Create a link button with borders
Another example of how to create link boxes/buttons.

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:
Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring

SHARE THIS PAGE

CSS Lists
Previous
Next Chapter

1. Coffee
2. Tea
3. Coca Cola

Coffee

Tea

Coca Cola

HTML Lists and CSS List Properties


In HTML, there are two main types of lists:

unordered lists (<ul>) - the list items are marked with bullets

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

The CSS list properties allow you to:

Set different list item markers for ordered lists

Set different list item markers for unordered lists

Set an image as the list item marker

Add background colors to lists and list items

Different List Item Markers


The list-style-type property specifies the type of list item marker.
The following example shows some of the available list item markers:

Example
ul.a {
list-style-type: circle;
}
ul.b {
list-style-type: square;
}
ol.c {

list-style-type: upper-roman;
}
ol.d {
list-style-type: lower-alpha;
}
Try it Yourself
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');
}
Try it Yourself

Position The List Item Markers


The list-style-position property specifies whether the list-item markers
should appear inside or outside the content flow:

Example
ul {
list-style-position: inside;
}
Try it Yourself

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");
}
Try it Yourself
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 are missing, the default value for the
missing property will be inserted, if any.

Styling List With Colors


We can also style lists with colors, to make them look a little more interesting.
Anything added to the <ol> or <ul> tag, affects the entire list, while properties
added to the <li> tag will affect the individual list items:

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

}
ul {
background: #3399ff;
padding: 20px;
}
ol li {
background: #ffe5e5;
padding: 5px;
margin-left: 35px;
}
ul li {
background: #cce5ff;
margin: 5px;
}
Result:
1. Coffee
2. Tea
3. Coca Cola

Coffee

Tea

Coca Cola

Try it Yourself

More Examples
Full-width bordered list
This example demonstrates how to create a bordered list without bullets.

All the different list-item markers for lists


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

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3

CSS Tables
Previous
Next Chapter

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


Company

Contact

Cou

Alfreds Futterkiste

Maria Anders

Germ

Berglunds snabbkp

Christina Berglund

Swe

Centro comercial Moctezuma

Francisco Chang

Mex

Ernst Handel

Roland Mendel

Aust

Island Trading

Helen Bennett

UK

Kniglich Essen

Philip Cramer

Germ

Laughing Bacchus Winecellars

Yoshi Tannamuri

Can

Magazzini Alimentari Riuniti

Giovanni Rovelli

Italy

Table Borders
To specify table borders in CSS, use the border property.
The example below specifies a black border for <table>, <th>, and <td> elements:

Example
table, th, td {
border: 1px solid black;
}
Try it Yourself

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

Collapse Table Borders


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

Example
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
Try it Yourself

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

Example

table {
border: 1px solid black;
}
Try it Yourself

Table Width and Height


Width and height of a table are defined by the width and height properties.
The example below sets the width of the table to 100%, and the height of the <th> elements to
50px:

Example
table {
width: 100%;
}
th {
height: 50px;
}
Try it Yourself

Horizontal Alignment
The text-align property sets the horizontal alignment (like left, right, or center) of the content
in <th> or <td>.
By default, the content of <th> elements are center-aligned and the content of <td> elements are
left-aligned.
The following example left-aligns the text in <th> elements:

Example

th {
text-align: left;
}
Try it Yourself

Vertical Alignment
The vertical-align property sets the vertical alignment (like top, bottom, or middle) of the
content in <th> or <td>.
By default, the vertical alignment of the content in a table is middle (for both <th> and <td>
elements).
The following example sets the vertical text alignment to bottom for <td> elements:

Example
td {
height: 50px;
vertical-align: bottom;
}
Try it Yourself

Table Padding
To control the space between the border and the content in a table, use the padding property on
<td> and <th> elements:

Example
th, td {
padding: 15px;
text-align: left;
}
Try it Yourself

Horizontal Dividers
First Name

Last Name

Savings

Peter

Griffin

$100

Lois

Griffin

$150

Joe

Swanson

$300

Add the border-bottom property to <th> and <td> for horizontal dividers:

Example
th, td {
border-bottom: 1px solid #ddd;
}
Try it Yourself

Hoverable Table
Use the :hover selector on <tr> to highlight table rows on mouse over:

First Name

Last Name

Savings

Peter

Griffin

$100

Lois

Griffin

$150

Joe

Swanson

$300

First Name

Last Name

Savings

Peter

Griffin

$100

Lois

Griffin

$150

Example
tr:hover {background-color: #f5f5f5}
Try it Yourself

Striped Tables

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}
Try it Yourself

Table Color
The example below specifies the background color and text color of <th> elements:

First Name

Last Name

Savings

Peter

Griffin

$100

Lois

Griffin

$150

Joe

Swanson

$300

Example
th {
background-color: #4CAF50;
color: white;
}
Try it Yourself

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

Point
s

Point
s

Point
s

Point
s

Point
s

Point
s

Point
s

Point
s

Jill

Smith

50

50

50

50

50

50

50

50

Eve

Jackson

94

94

94

94

94

94

94

94

Adam

Johnson

67

67

67

67

67

67

67

67

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

Example
<div style="overflow-x:auto;">
<table>
... table content ...
</table>

</div>
Try it Yourself

More Examples
Make a fancy table
This example demonstrates how to create a fancy table.
Set the position of the table caption
This example demonstrates how to position the table caption.

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4 Exercise 5 Exercise 6

CSS Table Properties


Property

Description

border

Sets all the border properties in one declaration

border-collapse

Specifies whether or not table borders should be collapsed

border-spacing

Specifies the distance between the borders of adjacent cells

caption-side

Specifies the placement of a table caption

empty-cells

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

table-layout

Sets the layout algorithm to be used for a table

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications
COLOR PICKER

LEARN MORE:

Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes

Color Palettes
Code Coloring
SHARE THIS PAGE

CSS Box Model


Previous

Next Chapter

The CSS Box Model


All HTML elements can be considered as boxes. 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

div {
width: 300px;
padding: 25px;
border: 25px solid navy;
margin: 25px;
}
Try it Yourself

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, yo
width and height of the content area. To calculate the full size of an element, you mu
padding, borders and margins.

Assume we want to style a <div> element to have a total width of 350px:

Example
div {
width: 320px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}
Try it Yourself
Here is the math:
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

Note for old IE: Internet Explorer 8 and earlier versions, include padding and border
property. To fix this problem, add a <!DOCTYPE html> to the HTML page.

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4

CSS Outline
Previous

Next Chapter

CSS Outline Properties


An outline is a line drawn around an element - outside the border. This can be
use to make an element "stand out".
The CSS outline properties specify the style, color, and width of an outline.
This element has a thin black border and a double outline that is 10px wide and
green.

CSS Outline
An outline is a line that is drawn around elements (outside the borders) to make
the element "stand out".
However, the outline property is different from the border property - The outline
is NOT a part of an element's dimensions; the element's total width and height
is not affected by the width of the outline.

Outline Style
The outline-style property specifies the style of the outline.
The outline-style property 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. The effect depends on the


outline-color value

ridge - Defines a 3D ridged outline. The effect depends on the outlinecolor value

inset - Defines a 3D inset outline. The effect depends on the outlinecolor value

outset - Defines a 3D outset outline. The effect depends on the outlinecolor value

none - Defines no outline

hidden - Defines a hidden outline

The following example first sets a thin black border around each <p> element,
then it shows the differentoutline-style values:

Example
p{
border: 1px solid black;
outline-color: red;
}
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.
Try it Yourself

Note: None of the OTHER CSS outline properties described below will have ANY effect

theoutline-style property is set!

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"

RGB - specify a RGB value, like "rgb(255,0,0)"

Hex - specify a hex value, like "#ff0000"

invert - performs a color inversion (which ensures that the outline is


visible, regardless of color background)

Example
p{
border: 1px solid black;
outline-style: double;
outline-color: red;
}
Result:
A colored outline.
Try it Yourself

Outline Width
The outline-width property specifies the width of the outline.

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
p {border: 1px solid black;}
p.one {
outline-style: double;
outline-color: red;
outline-width: thick;
}
p.two {
outline-style: double;
outline-color: green;
outline-width: 3px;
}
Result:
A thick outline.
A thinner outline.
Try it Yourself

Outline - Shorthand property


To shorten the code, it is also possible to specify all the individual outline
properties in one property.
The outline property is a shorthand property for the following individual
outline properties:

outline-width

outline-style (required)

outline-color

Example
p{
border: 1px solid black;
outline: 5px dotted red;
}
Result:
An outline.
Try it Yourself

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3

All CSS Outline Properties


Property

Description

outline

Sets all the outline properties in one declaration

outline-color

Sets the color of an outline

outline-offset

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

outline-style

Sets the style of an outline

outline-width

Sets the width of an outline

CSS Layout - The display Property


Previous
Next Chapter

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

The display Property


The display property specifies if/how an element is displayed.
Every HTML element has a default display value depending on what type of element it is. The
default display value for most elements is block or inline.
Click to show panel

Block-level Elements
A block-level element always starts on a new line and takes up the full width available (stretches
out to the left and right as far as it can).
The <div> element is a block-level element.
Examples of block-level elements:

<div>

<h1> - <h6>

<p>

<form>

<header>

<footer>

<section>

Inline Elements
An inline element does not start on a new line and only takes up as much width as necessary.
This is an inline <span> element inside a paragraph.
Examples of inline elements:

<span>

<a>

<img>

Display: none;
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.
display: none;

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

Override The Default Display Value


As mentioned, every element has a default display value. However, you can override this.
Changing an inline element to a block element, or vice versa, can be useful for making the page
look a specific way, and still follow the web standards.

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

Example
li {
display: inline;
}
Try it Yourself

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

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

Example
span {
display: block;
}
Try it Yourself

Hide an Element - display:none or


visibility:hidden?
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;
}
Try it Yourself
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;
}
Try it Yourself

More Examples
display: none; versus visibility: hidden;
This example demonstrates display: none; versus visibility: hidden;
Using CSS together with JavaScript to show content
This example demonstrates how to use CSS and JavaScript to show an element on click.

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4

CSS Display/Visibility Properties


Property

Description

display

Specifies how an element should be displayed

visibility

Specifies whether or not an element should be visible

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:
Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring

SHARE THIS PAGE

CSS Layout - width and max-width


Previous
Next Chapter

Using width, max-width and margin:


auto;
As mentioned in the previous chapter; a block-level element always takes up the full width
available (stretches out to the left and right as far as it can).
Setting the width of a block-level element will prevent it from stretching out to the edges of its
container. Then, you can set the margins to auto, to horizontally center the element within its
container. The element will take up the specified width, and the remaining space will be split
equally between the two margins:
This <div> element has a width of 500px, and margin set to auto.

Note: The problem with the <div> above occurs when the browser window is smaller than the
width of the element. The browser then adds a horizontal scrollbar to the page.
Using max-width instead, in this situation, will improve the browser's handling of small
windows. This is important when making a site usable on small devices:
This <div> element has a max-width of 500px, and margin set to auto.

Tip: Resize the browser window to less than 500px wide, to see the difference between the two
divs!
Here is an example of the two divs above:

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

border: 3px solid #73AD21;


}
Try it Yourself

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications
COLOR PICKER

LEARN MORE:

Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring
SHARE THIS PAGE

CSS Layout - The


position Property
Previous
Next Chapter

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

The position Property


The position property specifies the type of positioning method used for an element.
There are four different position values:

static

relative

fixed

absolute

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

position: static;
HTML elements are positioned static by default.
Static positioned elements are not affected by the top, bottom, left, and right properties.

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

Here is the CSS that is used:

Example
div.static {
position: static;
border: 3px solid #73AD21;
}
Try it Yourself

position: relative;
An element with position: relative; is positioned relative to its normal position.
Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it
to be adjusted away from its normal position. Other content will not be adjusted to fit into any
gap left by the element.
This <div> element has position: relative;

Here is the CSS that is used:

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

position: fixed;
An element with position: fixed; is positioned relative to the viewport, which means it
always stays in the same place even if the page is scrolled. The top, right, bottom, and left
properties are used to position the element.
A fixed element does not leave a gap in the page where it would normally have been located.
Notice the fixed element in the lower-right corner of the page. Here is the CSS that is used:

Example
div.fixed {
position: fixed;
bottom: 0;
right: 0;
width: 300px;
border: 3px solid #73AD21;
}
Try it Yourself
This <div> element has position: fixed;

position: absolute;
An element with position: absolute; is positioned relative to the nearest positioned ancestor
(instead of positioned relative to the viewport, like fixed).
However; if an absolute positioned element has no positioned ancestors, it uses the document
body, and moves along with page scrolling.
Note: A "positioned" element is one whose position is anything except static.
Here is a simple example:
This <div> element has position: relative;
This <div> element has position: absolute;

Here is the CSS that is used:

Example
div.relative {
position: relative;
width: 400px;
height: 200px;
border: 3px solid #73AD21;
}
div.absolute {
position: absolute;
top: 80px;
right: 0;
width: 200px;
height: 100px;
border: 3px solid #73AD21;
}
Try it Yourself

Overlapping Elements
When elements are positioned, they can overlap other elements.
The z-index property specifies the stack order of an element (which element should be placed in
front of, or behind, the others).
An element can have a positive or negative stack order:

This is a heading

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

Example
img {
position: absolute;
left: 0px;
top: 0px;
z-index: -1;
}
Try it Yourself
An element with greater stack order is always in front of an element with a lower stack order.

Note: If two positioned elements overlap without a z-index specified, the element positioned last in the
be shown on top.

Positioning Text In an Image


How to position text over an image:

Example

Bottom Left
Top Left

Top Right
Bottom Right
Centered
Try it Yourself:
Top Left Top Right Bottom Left Bottom Right Centered

More Examples
Set the shape of an element
This example demonstrates how to set the shape of an element. The element is clipped into this
shape, and displayed.
How to show overflow in an element using scroll
This example demonstrates how to set the overflow property to create a scroll bar when an
element's content is too big to fit in a specified area.
How to set the browser to automatically handle overflow
This example demonstrates how to set the browser to automatically handle overflow.
Change the cursor
This example demonstrates how to change the cursor.

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4 Exercise 5

All CSS Positioning Properties


Property

Description

bottom

Sets the bottom margin edge for a positioned box

clip

Clips an absolutely positioned element

cursor

Specifies the type of cursor to be displayed

left

Sets the left margin edge for a positioned box

overflow

Specifies what happens if content overflows an element's box

overflow-x

Specifies what to do with the left/right edges of the content if it overflows the e
content area

overflow-y

Specifies what to do with the top/bottom edges of the content if it overflows th


content area

position

Specifies the type of positioning for an element

right

Sets the right margin edge for a positioned box

top

Sets the top margin edge for a positioned box

z-index

Sets the stack order of an element

Previous
Next Chapter
W3SCHOOLS EXAMS

HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:
Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring

SHARE THIS PAGE

CSS Layout - float and clear


Previous
Next Chapter

The float property specifies whether or not an element should float.


The clear property is used to control the behavior of floating elements.

The float Property


In its simplest use, the float property can be used to wrap text around images.
The following example specifies that an image should float to the right in a text:

Example
img {
float: right;
margin: 0 0 10px 10px;
}
Try it Yourself

The clear Property


The clear property is used to control the behavior of floating elements.
Elements after a floating element will flow around it. To avoid this, use the clear property.
The clear property specifies on which sides of an element floating elements are not allowed to
float:

Example
div {
clear: left;
}
Try it Yourself

The clearfix Hack - overflow: auto;


If an element is taller than the element containing it, and it is floated, it will overflow outside of
its container.
Then we can add overflow: auto; to the containing element to fix this problem:

Example
.clearfix {
overflow: auto;
}
Try it Yourself

Web Layout Example


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

Example
div {
border: 3px solid blue;
}
.clearfix {
overflow: auto;
}
nav {
float: left;
width: 200px;
border: 3px solid #73AD21;
}
section {
margin-left: 206px;
border: 3px solid red;
}
Try it Yourself

More Examples
An image with border and margins that floats to the right in a paragraph
Let an image float to the right in a paragraph. Add border and margins to the image.
An image with a caption that floats to the right
Let an image with a caption float to the right.
Let the first letter of a paragraph float to the left
Let the first letter of a paragraph float to the left and style the letter.
Creating a horizontal menu
Use float with a list of hyperlinks to create a horizontal menu.
Creating a homepage without tables
Use float to create a homepage with a header, footer, left content and main content.

All CSS Float Properties


Property

Description

clear

Specifies on which sides of an element where floating elements are not allo

float

Specifies whether or not an element should float

overflow

Specifies what happens if content overflows an element's box

overflow-x

Specifies what to do with the left/right edges of the content if it overflows t


content area

overflow-y

Specifies what to do with the top/bottom edges of the content if it overflow


element's content area

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications
COLOR PICKER

LEARN MORE:

Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring
SHARE THIS PAGE

CSS Layout - inline-block


Previous
Next Chapter

The inline-block Value


It has been possible for a long time to create a grid of boxes that fills the
browser width and wraps nicely (when the browser is resized), by using
the float property.
However, the inline-block value of the display property makes this even easier.
inline-block elements are like inline elements but they can have a width and a
height.

Examples
The old way - using float (notice that we also need to specify a clear property
for the element after the floating boxes):

Example
.floating-box {
float: left;
width: 150px;
height: 75px;
margin: 10px;
border: 3px solid #73AD21;
}
.after-box {
clear: left;
}

Try it Yourself
The same effect can be achieved by using the inline-block value of
the display property (notice that noclear property is needed):

Example
.floating-box {
display: inline-block;
width: 150px;
height: 75px;
margin: 10px;
border: 3px solid #73AD21;
}

Try it Yourself

CSS Layout - Horizontal Align


Previous
Next Chapter

In CSS, several properties can be used to


align elements horizontally.
Center Align - Using margin
Setting the width of a block-level element will prevent it from stretching out to the edges of its
container. Usemargin: auto;, to horizontally center an element within 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: 60%;
border: 3px solid #73AD21;
padding: 10px;
}
Try it Yourself

Tip: Center aligning has no effect if the width property is not set (or set to 100%).
Tip: For aligning text, see the CSS Text chapter.

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;
}
Try it Yourself

Note: Absolute positioned elements are removed from the normal flow, and can overlap
elements.
Tip: When aligning elements with position, always define margin and padding for
the <body> element. This is to avoid visual differences in different browsers.
There is also a problem with IE8 and earlier, when using position. If a container element (in
our case <div class="container">) has a specified width, and the !DOCTYPE declaration is
missing, IE8 and earlier versions will add a 17px margin on the right side. This seems to be
space reserved for a scrollbar. So, always set the !DOCTYPE declaration when using position:

Example

body {
margin: 0;
padding: 0;
}
.container {
position: relative;
width: 100%;
}
.right {
position: absolute;
right: 0px;
width: 300px;
background-color: #b0e0e6;
}
Try it Yourself

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;
}
Try it Yourself

Tip: When aligning elements with float, always define margin and padding for
the <body> element. This is to avoid visual differences in different browsers.
There is also a problem with IE8 and earlier, when using float. If the !DOCTYPE declaration is
missing, IE8 and earlier versions will add a 17px margin on the right side. This seems to be
space reserved for a scrollbar. So, always set the !DOCTYPE declaration when using float:

Example

body {
margin: 0;
padding: 0;
}
.right {
float: right;
width: 300px;
background-color: #b0e0e6;
}
Try it Yourself

Test Yourself with Exercises!


Exercise 1 Exercise 2

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications
COLOR PICKER

LEARN MORE:

Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations

Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring
SHARE THIS PAGE

CSS Combinators
Previous
Next Chapter

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

descendant selector (space)

child selector (>)

adjacent sibling selector (+)

general sibling selector (~)

Descendant Selector
The descendant selector matches all elements that are descendants of a specified element.
The following example selects all <p> elements inside <div> elements:

Example
div p {
background-color: yellow;
}
Try it Yourself

Child Selector
The child selector selects all elements that are the immediate children of a specified element.
The following example selects all <p> elements that are immediate children of a <div> element:

Example
div > p {
background-color: yellow;
}
Try it Yourself

Adjacent Sibling Selector


The adjacent sibling selector selects all elements that are the adjacent siblings of a specified
element.
Sibling elements must have the same parent element, and "adjacent" means "immediately
following".
The following example selects all <p> elements that are placed immediately after <div>
elements:

Example
div + p {
background-color: yellow;
}
Try it Yourself

General Sibling Selector


The general sibling selector selects all elements that are siblings of a specified element.
The following example selects all <p> elements that are siblings of <div> elements:

Example
div ~ p {
background-color: yellow;
}
Try it Yourself

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:

Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring

SHARE THIS PAGE

CSS Pseudo-classes
Previous
Next Chapter

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;
}
Try it Yourself

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

Pseudo-classes and CSS Classes


Pseudo-classes can be combined with CSS classes:
When you hover over the link in the example, it will change color:

Example
a.highlight:hover {
color: #ff0000;
}
Try it Yourself

Hover on <div>
An example of using the :hover pseudo-class on a <div> element:

Example
div:hover {
background-color: blue;
}
Try it Yourself

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


In the following example, the selector matches any <p> element that is the first child of any
element:

Example
p:first-child {
color: blue;
}
Try it Yourself

Match the first <i> element in all <p>


elements
In the following example, the selector matches the first <i> element in all <p> elements:

Example
p i:first-child {
color: blue;
}
Try it Yourself

Match all <i> elements in all first child


<p> elements
In the following example, the selector matches all <i> elements in <p> elements that are the first
child of another element:

Example
p:first-child i {
color: blue;
}
Try it Yourself

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 <q> elements with lang="no":

Example
<html>
<head>
<style>
q:lang(no) {
quotes: "~" "~";
}
</style>
</head>
<body>
<p>Some text <q lang="no">A quote in a paragraph</q> Some text.</p>
</body>
</html>
Try it Yourself

More Examples
Add different styles to hyperlinks
This example demonstrates how to add other styles to hyperlinks.
Use of :focus
This example demonstrates how to use the :focus pseudo-class.

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4

All CSS Pseudo Classes


Selector

Example

Example description

:active

a:active

Selects the active link

:checked

input:checked

Selects every checked <input> element

:disabled

input:disabled

Selects every disabled <input> element

:empty

p:empty

Selects every <p> element that has no children

:enabled

input:enabled

Selects every enabled <input> element

:first-child

p:first-child

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

:first-of-type

p:first-of-type

Selects every <p> element that is the first <p> element of it

:focus

input:focus

Selects the <input> element that has focus

:hover

a:hover

Selects links on mouse over

:in-range

input:in-range

Selects <input> elements with a value within a specified ran

:invalid

input:invalid

Selects all <input> elements with an invalid value

:lang(language)

p:lang(it)

Selects every <p> element with a lang attribute value startin

:last-child

p:last-child

Selects every <p> elements that is the last child of its paren

:last-of-type

p:last-of-type

Selects every <p> element that is the last <p> element of its

:link

a:link

Selects all unvisited links

:not(selector)

:not(p)

Selects every element that is not a <p> element

:nth-child(n)

p:nth-child(2)

Selects every <p> element that is the second child of its par

:nth-last-child(n)

p:nth-last-child(2)

Selects every <p> element that is the second child of its par
from the last child

:nth-last-of-type(n)

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

Selects every <p> element that is the second <p> element o


counting from the last child

:nth-of-type(n)

p:nth-of-type(2)

Selects every <p> element that is the second <p> element o

:only-of-type

p:only-of-type

Selects every <p> element that is the only <p> element of it

:only-child

p:only-child

Selects every <p> element that is the only child of its paren

:optional

input:optional

Selects <input> elements with no "required" attribute

:out-of-range

input:out-of-range

Selects <input> elements with a value outside a specified ra

:read-only

input:read-only

Selects <input> elements with a "readonly" attribute specifi

:read-write

input:read-write

Selects <input> elements with no "readonly" attribute

:required

input:required

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

:root

root

Selects the document's root element

:target

#news:target

Selects the current active #news element (clicked on a URL


anchor name)

:valid

input:valid

Selects all <input> elements with a valid value

:visited

a:visited

Selects all visited links

All CSS Pseudo Elements


Selector

Example

Example description

::after

p::after

Insert content after every <p> element

::before

p::before

Insert content before every <p> element

::first-letter

p::first-letter

Selects the first letter of every <p> element

::first-line

p::first-line

Selects the first line of every <p> element

::selection

p::selection

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

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:
Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring

SHARE THIS PAGE

CSS Pseudo-elements
Previous
Next Chapter

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;
}
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 f
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-line Pseudo-element

The ::first-line pseudo-element is used to add a special style to the first line of a text.
The following example formats the first line of the text in all <p> elements:

Example
p::first-line {
color: #ff0000;
font-variant: small-caps;
}
Try it Yourself
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

The ::first-letter Pseudo-element


The ::first-letter pseudo-element is used to add a special style to the first letter of a text.
The following example formats the first letter of the text in all <p> elements:

Example
p::first-letter {
color: #ff0000;
font-size: xx-large;
}
Try it Yourself
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 CSS Classes


Pseudo-elements can be combined with CSS classes:

Example
p.intro::first-letter {
color: #ff0000;
font-size:200%;
}
Try it Yourself
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;
}
Try it Yourself

CSS - The ::before Pseudo-element


The ::before pseudo-element can be used to insert some content before the content of an
element.
The following example inserts an image before the content of each <h1> element:

Example
h1::before {
content: url(smiley.gif);
}
Try it Yourself

CSS - The ::after Pseudo-element


The ::after pseudo-element can be used to insert some content after the content of an
element.
The following example inserts an image after the content of each <h1> element:

Example
h1::after {
content: url(smiley.gif);
}
Try it Yourself

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;
}
Try it Yourself

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3

All CSS Pseudo Elements


Selector

Example

Example description

::after

p::after

Insert something after the content of each <p> element

::before

p::before

Insert something before the content of each <p> element

::first-letter

p::first-letter

Selects the first letter of each <p> element

::first-line

p::first-line

Selects the first line of each <p> element

::selection

p::selection

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

All CSS Pseudo Classes


Selector

Example

Example description

:active

a:active

Selects the active link

:checked

input:checked

Selects every checked <input> element

:disabled

input:disabled

Selects every disabled <input> element

:empty

p:empty

Selects every <p> element that has no children

:enabled

input:enabled

Selects every enabled <input> element

:first-child

p:first-child

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

:first-of-type

p:first-of-type

Selects every <p> element that is the first <p> element of it

:focus

input:focus

Selects the <input> element that has focus

:hover

a:hover

Selects links on mouse over

:in-range

input:in-range

Selects <input> elements with a value within a specified ran

:invalid

input:invalid

Selects all <input> elements with an invalid value

:lang(language)

p:lang(it)

Selects every <p> element with a lang attribute value startin

:last-child

p:last-child

Selects every <p> elements that is the last child of its paren

:last-of-type

p:last-of-type

Selects every <p> element that is the last <p> element of its

:link

a:link

Selects all unvisited links

:not(selector)

:not(p)

Selects every element that is not a <p> element

:nth-child(n)

p:nth-child(2)

Selects every <p> element that is the second child of its par

:nth-last-child(n)

p:nth-last-child(2)

Selects every <p> element that is the second child of its par
from the last child

:nth-last-of-type(n)

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

Selects every <p> element that is the second <p> element o


counting from the last child

:nth-of-type(n)

p:nth-of-type(2)

Selects every <p> element that is the second <p> element o

:only-of-type

p:only-of-type

Selects every <p> element that is the only <p> element of it

:only-child

p:only-child

Selects every <p> element that is the only child of its paren

:optional

input:optional

Selects <input> elements with no "required" attribute

:out-of-range

input:out-of-range

Selects <input> elements with a value outside a specified ra

:read-only

input:read-only

Selects <input> elements with a "readonly" attribute specifi

:read-write

input:read-write

Selects <input> elements with no "readonly" attribute

:required

input:required

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

:root

root

Selects the document's root element

:target

#news:target

Selects the current active #news element (clicked on a URL


anchor name)

:valid

input:valid

Selects all <input> elements with a valid value

:visited

a:visited

Selects all visited links

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:
Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation

HTML Includes
Color Palettes
Code Coloring

SHARE THIS PAGE

CSS Navigation Bar


Previous
Next Chapter

Demo: Navigation Bars


Vertical

Home

News

Contact

About
Horizontal

Home

News

Contact

About

Home

News

Contact

About

Navigation Bars
Having easy-to-use navigation is important for any web site.
With CSS you can transform boring HTML menus into good-looking navigation
bars.

Navigation Bar = List of Links


A navigation bar needs standard HTML as a base.
In our examples we will build the navigation bar from a standard HTML list.
A navigation bar is basically a list of links, so using the <ul> and <li> elements
makes perfect sense:

Example
<ul>
<li><a
<li><a
<li><a
<li><a
</ul>

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

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

Example
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
Try it Yourself
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.

Vertical Navigation Bar


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

Example
li a {
display: block;
width: 60px;
}
Try it Yourself
Example explained:

display: block; - Displaying the links as block elements makes the


whole link area clickable (not just the text), and it allows us to specify the
width (and padding, margin, height, etc. if you want)

width: 60px; - Block elements take up the full width available by


default. We want to specify a 60 pixels width

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

Example
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 60px;
}
li a {
display: block;
}
Try it Yourself

Vertical Navigation Bar Examples


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

Home

News

Contact

About

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

width: 200px;
background-color: #f1f1f1;
}
li a {
display: block;
color: #000;
padding: 8px 0 8px 16px;
text-decoration: none;
}
/* Change the link color on hover */
li a:hover {
background-color: #555;
color: white;
}
Try it Yourself

Active/Current Navigation Link


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

Home

News

Contact

About

Example
.active {
background-color: #4CAF50;
color: white;
}
Try it Yourself

Center Links & Add Borders

Add text-align:center to <li> or <a> to center the links.


Add the border property to <ul> add a border around the navbar. If you also
want borders inside the navbar, add a border-bottom to all <li> elements,
except for the last one:

Home

News

Contact
About

Example
ul {
border: 1px solid #555;
}
li {
text-align: center;
border-bottom: 1px solid #555;
}
li:last-child {
border-bottom: none;
}
Try it Yourself

Full-height Fixed Vertical Navbar


Create a full-height, "sticky" side navigation:

Example
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 25%;
background-color: #f1f1f1;

height: 100%; /* Full height */


position: fixed; /* Make it stick, even on scroll */
overflow: auto; /* Enable scrolling if the sidenav has too much content */
}
Try it Yourself
Note: This example might not work properly on mobile devices.

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 <li> elements as
inline, in addition to the "standard" code above:

Example
li {
display: inline;
}
Try it Yourself
Example explained:

display: inline; - By default, <li> 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 <li>
elements, and specify a layout for the navigation links:

Example

li {
float: left;
}
a{
display: block;
padding: 8px;
background-color: #dddddd;
}
Try it Yourself
Example explained:

float: left; - use float to get block elements to slide next to each
other

display: block; - Displaying the links as block elements makes the


whole link area clickable (not just the text), and it allows us to specify
padding (and height, width, margins, etc. if you want)

padding: 8px; - Since block elements take up the full width available,
they cannot float next to each other. Therefore, specify some padding to
make them look good

background-color: #dddddd; - Add a gray background-color to each a


element

Tip: Add the background-color to <ul> instead of each <a> element if you
want a full-width background color:

Example
ul {
background-color: #dddddd;
}
Try it Yourself

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:

Home

News

Contact

About

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;
}
Try it Yourself

Active/Current Navigation Link

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

Home

News

Contact

About

Example
.active {
background-color: #4CAF50;
}
Try it Yourself

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

Home

News

Contact

About

Example
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li style="float:right"><a class="active" href="#about">About</a></li>
</ul>
Try it Yourself

Border Dividers
Add the border-right property to <li> to create link dividers:

Home

News

Contact

About

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;
}
Try it Yourself

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%;
}
Try it Yourself

Fixed Bottom

ul {
position: fixed;
bottom: 0;
width: 100%;
}
Try it Yourself
Note: These examples might not work properly on mobile devices.

Gray Horizontal Navbar


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

Home

News

Contact

About

Example
ul {
border: 1px solid #e7e7e7;
background-color: #f3f3f3;
}
li a {
color: #666;
}
Try it Yourself

More Examples
Responsive Topnav
How to use CSS3 media queries to create a responsive top navigation.
Responsive Sidenav
How to use CSS3 media queries to create a responsive side navigation.
Dropdown Navbar
How to add a dropdown menu inside a navigation bar.

CSS Dropdowns
Previous
Next Chapter

Create a hoverable dropdown with CSS.

Demo: Dropdown Examples


Move the mouse over the examples below:
Dropdown Text
Dropdown Menu

Other:

Basic Dropdown

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

Example
<style>
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
padding: 12px 16px;
z-index: 1;
}
.dropdown:hover .dropdown-content {
display: block;
}
</style>
<div class="dropdown">
<span>Mouse over me</span>
<div class="dropdown-content">
<p>Hello World!</p>
</div>
</div>
Try it Yourself

Example Explained
HTML) Use any element to open the dropdown content, e.g. a <span>, or a <button> element.
Use a container element (like <div>) to create the dropdown content and add whatever you want
inside of it.
Wrap a <div> element around the elements to position the dropdown content correctly with CSS.
CSS) The .dropdown class use 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:autoto enable scroll on small screens).
Instead of using a border, we have used the CSS3 box-shadow property to make the dropdown
menu look like a "card".
The :hover selector is used to show the dropdown menu when the user moves the mouse over
the dropdown button.

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

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

Example
<style>
/* Style The Dropdown Button */
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
/* The container <div> - needed to position the dropdown content */
.dropdown {
position: relative;
display: inline-block;
}
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;

position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
/* Links inside the dropdown */
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #f1f1f1}
/* Show the dropdown menu on hover */
.dropdown:hover .dropdown-content {
display: block;
}
/* Change the background color of the dropdown button when the dropdown content
is shown */
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
</style>
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
Try it Yourself

Right-aligned Dropdown Content


Left

Right

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;
}
Try it Yourself

More Examples
Dropdown Image
This example demonstrates how to add an image and other content inside the dropdown box.
Dropdown Navbar
This example demonstrates how to add a dropdown menu inside a navigation bar.

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications
COLOR PICKER

LEARN MORE:

Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring
SHARE THIS PAGE

CSS Tooltip
Previous
Next Chapter

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
Right
Bottom

Left

Basic Tooltip
Create a tooltip that appears when the user moves the mouse over an element:

Example
<style>
/* Tooltip container */
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black; /* If you want dots under the hoverable text */
}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
/* Position the tooltip text - see examples below! */
position: absolute;
z-index: 1;
}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
visibility: visible;
}
</style>
<div class="tooltip">Hover over me
<span class="tooltiptext">Tooltip text</span>
</div>
Try it Yourself

Example Explained
HTML) Use a container element (like <div>) and add the "tooltip" class to it. When the user
mouse over this <div>, it will show the tooltip text.
The tooltip text is placed inside an inline element (like <span>) 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 CSS3 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
<div> withclass="tooltip".

Positioning Tooltips
In this example, the tooltip is placed to the right (left:105%) of the "hoverable" text (<div>).
Also note thattop:-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 topproperty 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
Try it Yourself

Left Tooltip
.tooltip .tooltiptext {
top: -5px;
right: 105%;
}

Result:
Hover over me
Try it Yourself

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
Try it Yourself

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
Try it Yourself

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
Try it Yourself

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
Try it Yourself

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
Try it Yourself

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
Try it Yourself

Fade In Tooltips (Animation)


If you want to fade in the tooltip text when it is about to be visible, you can use the
CSS3 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;
}
Try it Yourself

Note: You will learn more about transitions and animations later in our tutorial.

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:

Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring
SHARE THIS PAGE

CSS Image Gallery


Previous
Next Chapter

CSS can be used to create an image gallery.

Add a description of the image here

Add a description of the image here

Add a description of the image here

Add a description of the image here

Image Gallery
The following image gallery is created with CSS:

Example
<html>
<head>
<style>
div.img {
margin: 5px;
border: 1px solid #ccc;
float: left;
width: 180px;
}
div.img:hover {
border: 1px solid #777;
}
div.img img {
width: 100%;
height: auto;
}
div.desc {
padding: 15px;
text-align: center;
}

</style>
</head>
<body>
<div class="img">
<a target="_blank" href="fjords.jpg">
<img src="fjords.jpg" alt="Fjords" width="300" height="200">
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="img">
<a target="_blank" href="forest.jpg">
<img src="forest.jpg" alt="Forest" width="300" height="200">
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="img">
<a target="_blank" href="lights.jpg">
<img src="lights.jpg" alt="Northern Lights" width="300" height="200">
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="img">
<a target="_blank" href="mountains.jpg">
<img src="mountains.jpg" alt="Mountains" width="300" height="200">
</a>
<div class="desc">Add a description of the image here</div>
</div>
</body>
</html>
Try it Yourself

More Examples

Responsive Image Gallery


How to use CSS3 media queries to create a responsive image gallery.
Advanced: Clickable Modal Images (JS)
An example of how to use JavaScript together with CSS to display clicked images in a modal
box.

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications
COLOR PICKER

LEARN MORE:

Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring
SHARE THIS PAGE

CSS Image Opacity / Transparency


Previous
Next Chapter

Creating transparent images with CSS is easy.


The CSS opacity property is a part of the CSS3 recommendation.

Example 1 - Creating a Transparent


Image
The CSS3 property for transparency is opacity.
First we will show you how to create a transparent image with CSS.
Regular image:

The same image with transparency:

Look at the following CSS:

Example
img {
opacity: 0.4;
filter: alpha(opacity=40); /* For IE8 and earlier */
}
Try it Yourself

The opacity property can take a value from 0.0 - 1.0. The lower value, the more transparent.
IE8 and earlier use filter:alpha(opacity=x). The x can take a value from 0 - 100. A lower
value makes the element more transparent.

Example 2 - Image Transparency - Hover


Effect
Mouse over the images:

The CSS looks like this:

Example
img {
opacity: 0.4;
filter: alpha(opacity=40); /* For IE8 and earlier */
}
img:hover {
opacity: 1.0;
filter: alpha(opacity=100); /* For IE8 and earlier */
}

Try it Yourself

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.

Example 3 - Text in Transparent Box


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

The source code looks like this:

Example
<html>
<head>
<style>
div.background {
background: url(klematis.jpg) repeat;
border: 2px solid black;
}
div.transbox {
margin: 30px;
background-color: #ffffff;
border: 1px solid black;
opacity: 0.6;
filter: alpha(opacity=60); /* For IE8 and earlier */
}
div.transbox p {
margin: 5%;
font-weight: bold;
color: #000000;
}
</style>
</head>
<body>

<div class="background">
<div class="transbox">
<p>This is some text that is placed in the transparent box.</p>
</div>
</div>
</body>
</html>
Try it Yourself

First, we create a <div> element (class="background") with a background image, and a border.
Then we create another <div> (class="transbox") inside the first <div>. The <div
class="transbox"> have a background color, and a border - the div is transparent. Inside the
transparent <div>, we add some text inside a <p> element.

Test Yourself with Exercises!


Exercise 1 Exercise 2

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications
COLOR PICKER

LEARN MORE:

Color Converter
Google Maps
Animated Buttons
Modal Boxes

Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring
SHARE THIS PAGE

CSS Image Sprites


Previous
Next Chapter

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

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;
}
Try it Yourself
Example explained:

<img id="home" src="img_trans.gif">

width: 46px; height: 44px;

background: url(img_navsprites.gif) 0 0;

- 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
- Defines the portion of the image we want to use
- 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;
}
Try it Yourself
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 is 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 are 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:

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;
}
Try it Yourself
Example explained:

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


all three hover images we specify the same background position, only 45px further down

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:
Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation

HTML Includes
Color Palettes
Code Coloring

SHARE THIS PAGE

CSS Attribute Selectors


Previous
Next Chapter

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 <a> elements with a target attribute:

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

Try it Yourself

CSS [attribute="value"] Selector


The [attribute="value"] selector is used to select elements with a specified
attribute and value.
The following example selects all <a> elements with a target="_blank"
attribute:

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

Try it Yourself

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

Try it Yourself
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 starting with the specified value.
The following example selects all elements with a class attribute value that
begins with "top":
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;
}

Try it Yourself

CSS [attribute^="value"] Selector


The [attribute^="value"] selector is used to select elements whose attribute
value begins with a specified value.
The following example selects all elements with a class attribute value that
begins with "top":
Note: The value does not have to be a whole word!

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

Try it Yourself

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

Try it Yourself

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

Try it Yourself

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

Try it Yourself
Tip: Visit our CSS Forms Tutorial for more examples on how to style forms with
CSS.

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4 Exercise 5 Exercise 6

More Examples of CSS Selectors


Use our CSS Selector Tester to demonstrate the different selectors.
For a complete reference of all the CSS selectors, please go to our CSS
Selectors Reference.

CSS Forms
Previous
Next Chapter

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


First Name

Last Name

State

Try it Yourself

Styling Input Fields


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

Example
input {
width: 100%;
}
Try it Yourself
The example above applies to all <input> elements. If you only want to style a specific input
type, you can use attribute selectors:

input[type=text] - will only select text fields

input[type=password] - will only select password fields

input[type=number] - will only select number fields

etc..

Padded Inputs
Use the padding property to add space inside the text field.
Tip: When you have many inputs after each other, you might also want to add some margin, to
add more space outside of them:
First Name

Last Name

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

Note that we have set the box-sizing property to border-box. This makes sure that the padding an
borders are included in the total width and height of the elements.
Read more about the box-sizing property in our CSS3 Box Sizing chapter.

Bordered Inputs
Use the border property to change the border size and color, and use the borderradius property to add rounded corners:
First Name

Example
input[type=text] {
border: 2px solid red;
border-radius: 4px;
}
Try it Yourself
If you only want a bottom border, use the border-bottom property:
First Name

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

Try it Yourself

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

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

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;
}
Try it Yourself

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

Try it Yourself

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;
}
Try it Yourself

Animated Search Input


In this example we use the CSS3 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 CSS3 Transitions chapter.

Example
input[type=text] {
-webkit-transition: width 0.4s ease-in-out;
transition: width 0.4s ease-in-out;
}
input[type=text]:focus {
width: 100%;
}
Try it Yourself

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;
}
Try it Yourself

Styling Select Menus


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

Styling Input Buttons


Example
input[type=button], input[type=submit], input[type=reset] {
background-color: #4CAF50;
border: none;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
}
/* Tip: use width: 100% for full-width buttons */
Try it Yourself
For more information about how to style buttons with CSS, read our CSS Buttons Tutorial.

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:
Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations

Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring

SHARE THIS PAGE

CSS Counters
Previous
Next Chapter

Using CSS 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) ": ";
}
Try it Yourself

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) " ";
}
Try it Yourself

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,".") " ";
}
Try it Yourself

CSS Counter Properties


Property

Description

content

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

counter-increment

Increments one or more counter values

counter-reset

Creates or resets one or more counters

CSS3 Introduction

Previous
Next Chapter
CSS3

CSS3 is the latest standard for CSS.


CSS3 is completely backwards-compatible with earlier versions of CSS.
This section teaches you about the new features in CSS3!

CSS3 Modules
CSS3 has been split into "modules". It contains the "old CSS specification"
(which has been split into smaller pieces). In addition, new modules are added.
Some of the most important CSS3 modules are:

Selectors

Box Model

Backgrounds and Borders

Image Values and Replaced Content

Text Effects

2D/3D Transformations

Animations

Multiple Column Layout

User Interface

Most of the new CSS3 properties are implemented in modern browsers.

CSS3 Rounded Corners


Previous

Next Chapter

CSS3 Rounded Corners


With the CSS3 border-radius property, you can give any element "rounded
corners".

Browser Support
The numbers in the table specify the first browser version that fully supports the
property.
Numbers followed by -webkit- or -moz- specify the first version that worked
with a prefix.

Property
border-radius

5.0
4.0 -webkit-

9.0

4.0
3.0 -moz-

5.0
3.1 -webkit-

CSS3 border-radius Property


With CSS3, you can give any element "rounded corners", by using the borderradius property.

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

Try it Yourself

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

CSS3 border-radius - Specify Each Corner


If you specify only one value for the border-radius property, this radius will
be applied to all 4 corners.
However, you can specify each corner separately if you wish. Here are the rules:

Four values: first value applies to top-left, second value applies to topright, third value applies to bottom-right, and fourth value applies to
bottom-left corner

Three values: first value applies to top-left, second value applies to topright and bottom-left, and third value applies to bottom-right

Two values: first value applies to top-left and bottom-right corner, and
the second value applies to top-right and bottom-left corner

One value: all four corners are rounded equally

Here are three examples:


1. Four values - border-radius: 15px 50px 30px 5px:
2. Three values - border-radius: 15px 50px 30px:
3. Two values - border-radius: 15px 50px:
Here is the code:

Example

#rcorners4 {
border-radius: 15px 50px 30px 5px;
background: #73AD21;
padding: 20px;
width: 200px;
height: 150px;
}
#rcorners5 {
border-radius: 15px 50px 30px;
background: #73AD21;
padding: 20px;
width: 200px;
height: 150px;
}
#rcorners6 {
border-radius: 15px 50px;
background: #73AD21;
padding: 20px;
width: 200px;
height: 150px;
}
Try it Yourself
You could also create elliptical corners:

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

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

Test Yourself with Exercises!


Exercise 1 Exercise 2

CSS3 Rounded Corners Properties


Property

Description

border-radius

A shorthand property for setting all the four border-*-*-radi

border-top-left-radius

Defines the shape of the border of the top-left corner

border-top-right-radius

Defines the shape of the border of the top-right corner

border-bottom-right-radius

Defines the shape of the border of the bottom-right corner

border-bottom-left-radius

Defines the shape of the border of the bottom-left corner

CSS3 Border Images


Previous
Next Chapter

CSS3 Border Images


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

Browser Support
The numbers in the table specify the first browser version that fully supports the property.
Numbers followed by -webkit-, -moz-, or -o- specify the first version that worked with a prefix.
Property
border-image

16.0
4.0 -webkit-

11.0

15.0
3.5 -moz-

CSS3 border-image Property


The CSS3 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

6.0
3.1 -webkit-

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;
-webkit-border-image: url(border.png) 30 round; /* Safari 3.1-5 */
-o-border-image: url(border.png) 30 round; /* Opera 11-12.1 */
border-image: url(border.png) 30 round;
}
Try it Yourself
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;
-webkit-border-image: url(border.png) 30 stretch; /* Safari 3.1-5 */
-o-border-image: url(border.png) 30 stretch; /* Opera 11-12.1 */
border-image: url(border.png) 30 stretch;
}

Try it Yourself

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

CSS3 border-image - Different Slice


Values
Different slice values completely changes the look of the border:
Example 1:
border-image: url(border.png) 50 round;
Example 2:
border-image: url(border.png) 20% round;
Example 3:
border-image: url(border.png) 30% round;
Here is the code:

Example
#borderimg1 {
border: 10px solid transparent;
padding: 15px;
-webkit-border-image: url(border.png) 50 round; /* Safari 3.1-5 */
-o-border-image: url(border.png) 50 round; /* Opera 11-12.1 */
border-image: url(border.png) 50 round;
}
#borderimg2 {
border: 10px solid transparent;
padding: 15px;
-webkit-border-image: url(border.png) 20% round; /* Safari 3.1-5 */
-o-border-image: url(border.png) 20% round; /* Opera 11-12.1 */

border-image: url(border.png) 20% round;


}
#borderimg3 {
border: 10px solid transparent;
padding: 15px;
-webkit-border-image: url(border.png) 30% round; /* Safari 3.1-5 */
-o-border-image: url(border.png) 30% round; /* Opera 11-12.1 */
border-image: url(border.png) 30% round;
}
Try it Yourself

Test Yourself with Exercises!


Exercise 1 Exercise 2

CSS3 Border Properties


Property

Description

border-image

A shorthand property for setting all the border-image-* properties

border-image-source

Specifies the path to the image to be used as a border

border-image-slice

Specifies how to slice the border image

border-image-width

Specifies the widths of the border image

border-image-outset

Specifies the amount by which the border image area extends beyond the

border-image-repeat

Specifies whether the border image should be repeated, rounded or stretc

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:
Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring

SHARE THIS PAGE

CSS3 Backgrounds
Previous

Next Chapter

CSS3 Backgrounds
CSS3 contains a few new background properties, which allow greater control of
the background element.
In this chapter you will learn how to add multiple background images to one
element.
You will also learn about the following new CSS3 properties:

background-size

background-origin

background-clip

Browser Support
The numbers in the table specify the first browser version that fully supports the
property.
Numbers followed by -webkit-, -moz-, or -o- specify the first version that
worked with a prefix.

Property
background-image
(with multiple backgrounds)

4.0

9.0

3.6

3.1

4.0
1.0 -webkit-

9.0

4.0
3.6 -moz-

4.1
3.0 -webkit-

background-origin

1.0

9.0

4.0

3.0

background-clip

4.0

9.0

4.0

3.0

background-size

CSS3 Multiple Backgrounds


CSS3 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;
}
Try it Yourself
Multiple background images can be specified using either the individual
background properties (as above) or thebackground 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;
}
Try it Yourself

CSS3 Background Size

The CSS3 background-size property allows you to specify the size of


background images.
Before CSS3, the size of a background image was the actual size of the image.
CSS3 allows us to re-use background images in different contexts.
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):
Original background image:

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.
Resized background image:

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;
}
Try it Yourself
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;
}
Try it Yourself

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_flwr.gif) left top no-repeat, url(img_flwr.gif) right
bottom no-repeat, url(paper.gif) left top repeat;
background-size: 50px, 130px, auto;
}
Try it Yourself

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 html element (the html
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_flower.jpg) no-repeat center fixed;
background-size: cover;
}

Try it Yourself

CSS3 background-origin Property


The CSS3 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;
}
Try it Yourself

CSS3 background-clip Property


The CSS3 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;
}
Try it Yourself

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4 Exercise 5

CSS3 Background Properties


Property

Description

background

A shorthand property for setting all the background properties


declaration

background-clip

Specifies the painting area of the background

background-image

Specifies one or more background images for an element

background-origin

Specifies where the background image(s) is/are positioned

background-size

Specifies the size of the background image(s)

CSS3 Colors
Previous

CSS3 Colors
CSS supports color names, hexadecimal and RGB colors.
In addition, CSS3 also introduces:

RGBA colors

HSL colors

HSLA colors

opacity

Browser Support

Next Chapter

The numbers in the table specify the first browser version that fully supports
CSS3 color values/property.

Property
RGBA, HSL, and HSLA

4.0

9.0

3.0

3.1

opacity

4.0

9.0

2.0

3.1

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,
rgba(255,
rgba(255,
rgba(255,

0,
0,
0,
0,

0,
0,
0,
0,

0.2);
0.4);
0.6);
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 */
Try it Yourself

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):
o 0 (or 360) is red
o 120 is green
o 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,
hsl(0,
hsl(0,
hsl(0,

100%,
100%,
100%,
100%,

30%);
50%);
70%);
90%);

The following example defines different HSL colors:

Example
#p1
#p2
#p3
#p4

{background-color:
{background-color:
{background-color:
{background-color:

hsl(120,
hsl(120,
hsl(120,
hsl(120,

100%, 50%);}
100%, 75%);}
100%, 25%);}
60%, 70%);}

/* green */
/* light green */
/* dark green */
/* pastel green */

Try it Yourself

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,
hsla(0,
hsla(0,
hsla(0,

100%,
100%,
100%,
100%,

30%,
50%,
70%,
90%,

0.3);
0.3);
0.3);
0.3);

The following example defines different HSLA colors:

Example
#p1 {background-color:
*/
#p2 {background-color:
opacity */
#p3 {background-color:
opacity */
#p4 {background-color:
opacity */

hsla(120, 100%, 50%, 0.3);} /* green with opacity


hsla(120, 100%, 75%, 0.3);} /* light green with
hsla(120, 100%, 25%, 0.3);} /* dark green with
hsla(120, 60%, 70%, 0.3);} /* pastel green with

Try it Yourself

Opacity
The CSS3 opacity property sets the opacity for a specified RGB value.
The opacity property value must be a number between 0.0 (fully transparent)
and 1.0 (fully opaque).
rgb(255,
rgb(255,
rgb(255,
rgb(255,

0,
0,
0,
0,

0);opacity:0.2;
0);opacity:0.4;
0);opacity:0.6;
0);opacity:0.8;

Notice that the text above will also be opaque.

The following example shows different RGB values 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 */
Try it Yourself

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4

CSS3 Gradients
Previous
Next Chapter

Gradient Background
CSS3 gradients let you display smooth transitions between two or more
specified colors.
Earlier, you had to use images for these effects. However, by using CSS3
gradients you can reduce download time and bandwidth usage. In addition,
elements with gradients look better when zoomed, because the gradient is
generated by the browser.
CSS3 defines two types of gradients:

Linear Gradients (goes down/up/left/right/diagonally)

Radial Gradients (defined by their center)

Browser Support
The numbers in the table specify the first browser version that fully supports the
property.
Numbers followed by -webkit-, -moz-, or -o- specify the first version that
worked with a prefix.

Property
linear-gradient

26.0
10.0 -webkit-

10.0

16.0
3.6 -moz-

6.1
5.1 -webkit-

radial-gradient

26.0
10.0 -webkit-

10.0

16.0
3.6 -moz-

6.1
5.1 -webkit-

repeating-linear-gradient

26.0
10.0 -webkit-

10.0

16.0
3.6 -moz-

6.1
5.1 -webkit-

repeating-radial-gradient

26.0
10.0 -webkit-

10.0

16.0
3.6 -moz-

6.1
5.1 -webkit-

CSS3 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: linear-gradient(direction, color-stop1, color-stop2, ...);
Linear Gradient - Top to Bottom (this is default)
The following example shows a linear gradient that starts at the top. It starts
red, transitioning to yellow:

Example
#grad {
background:
background:
background:
background:
background:
}

red; /* For browsers that do not support gradients */


-webkit-linear-gradient(red, yellow); /* For Safari 5.1 to 6.0 */
-o-linear-gradient(red, yellow); /* For Opera 11.1 to 12.0 */
-moz-linear-gradient(red, yellow); /* For Firefox 3.6 to 15 */
linear-gradient(red, yellow); /* Standard syntax */

Try it Yourself
Linear Gradient - Left to Right
The following example shows a linear gradient that starts from the left. It starts
red, transitioning to yellow:

Example
#grad {
background:
background:
6.0 */
background:
*/
background:
*/
background:
}

red; /* For browsers that do not support gradients */


-webkit-linear-gradient(left, red , yellow); /* For Safari 5.1 to
-o-linear-gradient(right, red, yellow); /* For Opera 11.1 to 12.0
-moz-linear-gradient(right, red, yellow); /* For Firefox 3.6 to 15
linear-gradient(to right, red , yellow); /* Standard syntax */

Try it Yourself
Linear Gradient - 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:

Example
#grad {
background: red; /* For browsers that do not support gradients */

background:
6.0 */
background:
to 12.0 */
background:
3.6 to 15 */
background:
syntax */
}

-webkit-linear-gradient(left top, red, yellow); /* For Safari 5.1 to


-o-linear-gradient(bottom right, red, yellow); /* For Opera 11.1
-moz-linear-gradient(bottom right, red, yellow); /* For Firefox
linear-gradient(to bottom right, red, yellow); /* Standard

Try it Yourself

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

Syntax
background: linear-gradient(angle, color-stop1, color-stop2);
The angle is specified as an angle between a horizontal line and the gradient
line.
The following example shows how to use angles on linear gradients:

Example
#grad {
background:
background:
6.0 */
background:
12.0 */
background:
15 */
background:
}

red; /* For browsers that do not support gradients */


-webkit-linear-gradient(-90deg, red, yellow); /* For Safari 5.1 to
-o-linear-gradient(-90deg, red, yellow); /* For Opera 11.1 to
-moz-linear-gradient(-90deg, red, yellow); /* For Firefox 3.6 to
linear-gradient(-90deg, red, yellow); /* Standard syntax */

Try it Yourself

Using Multiple Color Stops


The following example shows a linear gradient (from top to bottom) with
multiple color stops:

Example
#grad {
background:
background:
6.0 */
background:
*/
background:
*/
background:
}

red; /* For browsers that do not support gradients */


-webkit-linear-gradient(red, yellow, green); /* For Safari 5.1 to
-o-linear-gradient(red, yellow, green); /* For Opera 11.1 to 12.0
-moz-linear-gradient(red, yellow, green); /* For Firefox 3.6 to 15
linear-gradient(red, yellow, green); /* Standard syntax */

Try it Yourself
The following example shows how to create a linear gradient (from left to right)
with the color of the rainbow and some text:

Gradient Background
Example
#grad {
background: red; /* For browsers that do not support gradients */
/* For Safari 5.1 to 6.0 */
background: -webkit-lineargradient(left,red,orange,yellow,green,blue,indigo,violet);
/* For Opera 11.1 to 12.0 */
background: -o-lineargradient(left,red,orange,yellow,green,blue,indigo,violet);
/* For Fx 3.6 to 15 */
background: -moz-lineargradient(left,red,orange,yellow,green,blue,indigo,violet);
/* Standard syntax */
background: linear-gradient(to right,

red,orange,yellow,green,blue,indigo,violet);
}
Try it Yourself

Using Transparency
CSS3 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: red; /* For browsers that do not support gradients */
background: -webkit-lineargradient(left,rgba(255,0,0,0),rgba(255,0,0,1)); /*Safari 5.1-6*/
background: -o-lineargradient(right,rgba(255,0,0,0),rgba(255,0,0,1)); /*Opera 11.1-12*/
background: -moz-lineargradient(right,rgba(255,0,0,0),rgba(255,0,0,1)); /*Fx 3.6-15*/
background: linear-gradient(to right, rgba(255,0,0,0),
rgba(255,0,0,1)); /*Standard*/
}
Try it Yourself

Repeating a linear-gradient
The repeating-linear-gradient() function is used to repeat linear gradients:

Example
A repeating linear gradient:

#grad {
background: red; /* For browsers that do not support gradients */
/* Safari 5.1 to 6.0 */
background: -webkit-repeating-linear-gradient(red, yellow 10%, green 20%);
/* Opera 11.1 to 12.0 */
background: -o-repeating-linear-gradient(red, yellow 10%, green 20%);
/* Firefox 3.6 to 15 */
background: -moz-repeating-linear-gradient(red, yellow 10%, green 20%);
/* Standard syntax */
background: repeating-linear-gradient(red, yellow 10%, green 20%);
}
Try it Yourself

CSS3 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: 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: red; /* For browsers that do not support gradients */
background: -webkit-radial-gradient(red, yellow, green); /* Safari 5.1 to 6.0
*/
background: -o-radial-gradient(red, yellow, green); /* For Opera 11.6 to 12.0

*/
background: -moz-radial-gradient(red, yellow, green); /* For Firefox 3.6 to
15 */
background: radial-gradient(red, yellow, green); /* Standard syntax */
}
Try it Yourself
Radial Gradient - Differently Spaced Color Stops
The following example shows a radial gradient with differently spaced color
stops:

Example
#grad {
background: red; /* For browsers that do not support gradients */
background: -webkit-radial-gradient(red 5%, yellow 15%, green 60%); /*
Safari 5.1-6.0 */
background: -o-radial-gradient(red 5%, yellow 15%, green 60%); /* For
Opera 11.6-12.0 */
background: -moz-radial-gradient(red 5%, yellow 15%, green 60%); /* For
Firefox 3.6-15 */
background: radial-gradient(red 5%, yellow 15%, green 60%); /* Standard
syntax */
}
Try it Yourself

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: red; /* For browsers that do not support gradients */
background: -webkit-radial-gradient(circle, red, yellow, green); /* Safari */
background: -o-radial-gradient(circle, red, yellow, green); /* Opera 11.6 to

12.0 */
background: -moz-radial-gradient(circle, red, yellow, green); /* Firefox 3.6 to
15 */
background: radial-gradient(circle, red, yellow, green); /* Standard syntax */
}
Try it Yourself

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: red; /* For browsers that do not support gradients */
/* Safari 5.1 to 6.0 */
background: -webkit-radial-gradient(60% 55%, closest-side, red, yellow,
black);
/* For Opera 11.6 to 12.0 */
background: -o-radial-gradient(60% 55%, closest-side, red, yellow, black);
/* For Firefox 3.6 to 15 */
background: -moz-radial-gradient(60% 55%, closest-side, red, yellow,
black);
/* Standard syntax */
background: radial-gradient(closest-side at 60% 55%, red, yellow, black);
}
#grad2 {
/* Safari 5.1 to 6.0 */
background: -webkit-radial-gradient(60% 55%, farthest-side, red, yellow,

black);
/* Opera 11.6 to 12.0 */
background: -o-radial-gradient(60% 55%, farthest-side, red, yellow, black);
/* For Firefox 3.6 to 15 */
background: -moz-radial-gradient(60% 55%, farthest-side, red, yellow,
black);
/* Standard syntax */
background: radial-gradient(farthest-side at 60% 55%, red, yellow, black);
}
Try it Yourself

Repeating a radial-gradient
The repeating-radial-gradient() function is used to repeat radial gradients:

Example
A repeating radial gradient:

#grad {
background: red; /* For browsers that do not support gradients */
/* For Safari 5.1 to 6.0 */
background: -webkit-repeating-radial-gradient(red, yellow 10%, green 15%);
/* For Opera 11.6 to 12.0 */
background: -o-repeating-radial-gradient(red, yellow 10%, green 15%);
/* For Firefox 3.6 to 15 */
background: -moz-repeating-radial-gradient(red, yellow 10%, green 15%);
/* Standard syntax */
background: repeating-radial-gradient(red, yellow 10%, green 15%);
}
Try it Yourself

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4 Exercise 5 Exercise 6
Exercise 7

CSS3 Shadow Effects


Previous

Next Chapter

Box Shadow

With CSS3 you can create shadow


effects!
Hover over me!

CSS3 Shadow Effects


With CSS3 you can add shadow to text and to elements.
In this chapter you will learn about the following properties:

text-shadow

box-shadow

Browser Support
The numbers in the table specify the first browser version that fully supports the
property.
Numbers followed by -webkit- or -moz- specifies the first version that worked
with a prefix.

Property
text-shadow

4.0

10.0

3.5

4.0

box-shadow

10.0
4.0 -webkit-

9.0

4.0
3.5 -moz-

5.1
3.1 -webkit-

CSS3 Text Shadow


The CSS3 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;
}
Try it Yourself
Next, add a color to the shadow:

Text shadow effect!


Example
h1 {
text-shadow: 2px 2px red;
}
Try it Yourself
Then, add a blur effect to the shadow:

Text shadow effect!


Example
h1 {
text-shadow: 2px 2px 5px red;
}
Try it Yourself
The following example shows a white text with black shadow:

Text shadow effect!


Example
h1 {
color: white;
text-shadow: 2px 2px 4px #000000;
}
Try it Yourself
The following example shows a red neon glow shadow:

Text shadow effect!


Example
h1 {
text-shadow: 0 0 3px #FF0000;
}
Try it Yourself

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;
}
Try it Yourself
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;
}
Try it Yourself

CSS3 box-shadow Property


The CSS3 box-shadow property applies shadow to elements.
In its simplest use, you only specify the horizontal shadow and the vertical
shadow:
This is a yellow <div> element with a black box-shadow

Example
div {
box-shadow: 10px 10px;
}
Try it Yourself
Next, add a color to the shadow:
This is a yellow <div> element with a grey box-shadow

Example
div {
box-shadow: 10px 10px grey;
}
Try it Yourself
Next, add a blur effect to the shadow:
This is a yellow <div> element with a blurred, grey box-shadow

Example
div {
box-shadow: 10px 10px 5px grey;
}
Try it Yourself
You can also add shadows to the ::before and ::after pseudo-classes, to create
an interesting effect:

Example
#boxshadow {
position: relative;
box-shadow: 1px 2px 4px rgba(0, 0, 0, .5);
padding: 10px;
background: white;
}
#boxshadow img {
width: 100%;
border: 1px solid #8a4419;
border-style: inset;
}
#boxshadow::after {
content: '';
position: absolute;
z-index: -1; /* hide shadow behind image */
box-shadow: 0 15px 20px rgba(0, 0, 0, 0.3);
width: 70%;
left: 15%; /* one half of the remaining 30% */
height: 100px;
bottom: 0;
}
Try it Yourself

Cards
An example of using the box-shadow property to create paper-like cards:

1
January 1, 2016

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;
}
Try it (Text Card) Try it (Image Card)

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4 Exercise 5

CSS3 Shadow Properties


The following table lists the CSS3 shadow properties:

Property

Description

box-shadow

Adds one or more shadows to an element

text-shadow

Adds one or more shadows to a text

Previous
Next Chapter

CSS3 Text
Previous

Next Chapter

CSS3 Text
CSS3 contains several new text features.
In this chapter you will learn about the following text properties:

text-overflow

word-wrap

word-break

Browser Support
The numbers in the table specify the first browser version that fully supports the
property.
Numbers followed by -o- specify the first version that worked with a prefix.

Property
text-overflow

4.0

6.0

7.0

3.1

word-wrap

23.0

5.5

3.5

6.1

word-break

4.0

5.5

15.0

3.1

CSS3 Text Overflow


The CSS3 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;
}
Try it Yourself
The following example shows how you can display the overflowed content when
hovering over the element:

Example
div.test:hover {
text-overflow: inherit;
overflow: visible;
}
Try it Yourself

CSS3 Word Wrapping


The CSS3 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;
}
Try it Yourself

CSS3 Word Breaking


The CSS3 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;
}
Try it Yourself

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3

CSS3 Text Properties


The following table lists the new CSS3 text properties:

Property

Description

text-align-last

Specifies how to align the last line of a text

text-emphasis

A shorthand for setting text-emphasis-style and text-emphasis


declaration

text-justify

Specifies how justified text should be aligned and spaced

text-overflow

Specifies how overflowed content that is not displayed should


to the user

word-break

Specifies line breaking rules for non-CJK scripts

word-wrap

Allows long words to be able to be broken and wrap onto the n

CSS3 Web Fonts

Previous
Next Chapter

CSS3 Web Fonts - The @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 CSS3 @font-face rule.

Browser Support
The numbers in the table specify the first browser version that fully supports the property.
Property
@font-face

4.0

9.0

3.5

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.

3.2

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

WOFF

9.0

5.0

3.6

5.1

WOFF2

Not supported

36.0

35.0*

Not supported

SVG

Not supported

4.0

Not supported

3.2

EOT

6.0

Not supported

Not supported

Not supported

*IE: The font format only works when set to be "installable".


*Firefox: Not supported by default, but can be enabled (need to set a flag to "true" to use
WOFF2).

Using The Font You Want


In the CSS3 @font-face rule you must 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

To use the font for an HTML element, refer to the name of the font (myFirstFont) through
the font-familyproperty:

Example
@font-face {
font-family: myFirstFont;
src: url(sansation_light.woff);
}
div {
font-family: myFirstFont;
}
Try it Yourself

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;
}
Try it Yourself

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 1 Exercise 2

CSS3 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. Def


"normal"

font-style

normal
italic
oblique

Optional. Defines how the font should be styled. Defaul

font-weight

normal
bold
100
200
300
400
500
600
700
800
900

Optional. Defines the boldness of the font. Default is "n

unicode-range

unicode-range

Optional. Defines the range of UNICODE characters the


supports. Default is "U+0-10FFFF"

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:

Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring
SHARE THIS PAGE

CSS3 2D Transforms
Previous

Next Chapter

CSS3 Transforms
CSS3 transforms allow you to translate, rotate, scale, and skew elements.
A transformation is an effect that lets an element change shape, size and
position.

CSS3 supports 2D and 3D transformations.


Mouse over the elements below to see the difference between a 2D and a 3D
transformation:
2D rotate
3D rotate

Browser Support for 2D Transforms


The numbers in the table specify the first browser version that fully supports the
property.
Numbers followed by -ms-, -webkit-, -moz-, or -o- specify the first version that
worked with a prefix.

Property
transform

36.0
4.0 -webkit-

10.0
9.0 -ms-

16.0
3.5 -moz-

3.2 -webkit-

transform-origin
(two-value syntax)

36.0
4.0 -webkit-

10.0
9.0 -ms-

16.0
3.5 -moz-

3.2 -webkit-

CSS3 2D Transforms
In this chapter you will learn about the following 2D transformation methods:

translate()

rotate()

scale()

skewX()

skewY()

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 <div> element 50 pixels to the right, and 100
pixels down from its current position:

Example
div {
-ms-transform: translate(50px,100px); /* IE 9 */
-webkit-transform: translate(50px,100px); /* Safari */
transform: translate(50px,100px);
}
Try it Yourself

The rotate() Method

The rotate() method rotates an element clockwise or counter-clockwise


according to a given degree.
The following example rotates the <div> element clockwise with 20 degrees:

Example
div {
-ms-transform: rotate(20deg); /* IE 9 */
-webkit-transform: rotate(20deg); /* Safari */
transform: rotate(20deg);
}
Try it Yourself
Using negative values will rotate the element counter-clockwise.
The following example rotates the <div> element counter-clockwise with 20
degrees:

Example
div {
-ms-transform: rotate(-20deg); /* IE 9 */
-webkit-transform: rotate(-20deg); /* Safari */
transform: rotate(-20deg);
}
Try it Yourself

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 <div> element to be two times of its
original width, and three times of its original height:

Example
div {
-ms-transform: scale(2,3); /* IE 9 */
-webkit-transform: scale(2,3); /* Safari */
transform: scale(2,3);
}
Try it Yourself
The following example decreases the <div> element to be half of its original
width and height:

Example
div {
-ms-transform: scale(0.5,0.5); /* IE 9 */
-webkit-transform: scale(0.5,0.5); /* Safari */
transform: scale(0.5,0.5);
}
Try it Yourself

The skewX() Method


The skewX() method skews an element along the X-axis by the given angle.

The following example skews the <div> element 20 degrees along the X-axis:

Example
div {
-ms-transform: skewX(20deg); /* IE 9 */
-webkit-transform: skewX(20deg); /* Safari */
transform: skewX(20deg);
}
Try it Yourself

The skewY() Method


The skewY() method skews an element along the Y-axis by the given angle.
The following example skews the <div> element 20 degrees along the Y-axis:

Example
div {
-ms-transform: skewY(20deg); /* IE 9 */
-webkit-transform: skewY(20deg); /* Safari */
transform: skewY(20deg);
}
Try it Yourself

The skew() Method


The skew() method skews an element along the X and Y-axis by the given
angles.
The following example skews the <div> element 20 degrees along the X-axis,
and 10 degrees along the Y-axis:

Example

div {
-ms-transform: skew(20deg, 10deg); /* IE 9 */
-webkit-transform: skew(20deg, 10deg); /* Safari */
transform: skew(20deg, 10deg);
}
Try it Yourself
If the second parameter is not specified, it has a zero value. So, the following
example skews the <div> element 20 degrees along the X-axis:

Example
div {
-ms-transform: skew(20deg); /* IE 9 */
-webkit-transform: skew(20deg); /* Safari */
transform: skew(20deg);
}
Try it Yourself

The matrix() Method

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 {
-ms-transform: matrix(1, -0.3, 0, 1, 0, 0); /* IE 9 */

-webkit-transform: matrix(1, -0.3, 0, 1, 0, 0); /* Safari */


transform: matrix(1, -0.3, 0, 1, 0, 0);
}
Try it Yourself

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4

CSS3 Transform Properties


The following table lists all the 2D transform properties:

Property

Description

transform

Applies a 2D or 3D transformation to an element

transform-origin

Allows you to change the position on transformed elements

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

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

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

Previous
Next Chapter

CSS3 3D Transforms
Previous
Next Chapter

CSS3 3D Transforms
CSS3 allows you to format your elements using 3D transformations.
Mouse over the elements below to see the difference between a 2D and a 3D transformation:
2D rotate
3D rotate

Browser Support for 3D Transforms


The numbers in the table specify the first browser version that fully supports the property.
Numbers followed by -webkit-, -moz-, or -o- specify the first version that worked with a prefix.
Property
transform

36.0
12.0 -webkit-

10.0

16.0
10.0 -moz-

4.0 -webkit-

transform-origin
(three-value syntax)

36.0
12.0 -webkit-

10.0

16.0
10.0 -moz-

4.0 -webkit-

transform-style

36.0
12.0 -webkit-

11.0

16.0
10.0 -moz-

4.0 -webkit-

perspective

36.0
12.0 -webkit-

10.0

16.0
10.0 -moz-

4.0 -webkit-

perspective-origin

36.0
12.0 -webkit-

10.0

16.0
10.0 -moz-

4.0 -webkit-

backface-visibility

36.0
12.0 -webkit-

10.0

16.0
10.0 -moz-

4.0 -webkit-

CSS3 3D Transforms
In this chapter you will learn about 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
div {
-webkit-transform: rotateX(150deg); /* Safari */
transform: rotateX(150deg);
}
Try it Yourself

The rotateY() Method

The rotateY() method rotates an element around its Y-axis at a given degree:

Example

div {
-webkit-transform: rotateY(130deg); /* Safari */
transform: rotateY(130deg);
}
Try it Yourself

The rotateZ() Method


The rotateZ() method rotates an element around its Z-axis at a given degree:

Example
div {
-webkit-transform: rotateZ(90deg); /* Safari */
transform: rotateZ(90deg);
}
Try it Yourself

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3

CSS3 Transform Properties


The following table lists all the 3D transform properties:

Property

Description

transform

Applies a 2D or 3D transformation to an element

transform-origin

Allows you to change the position on transformed elements

transform-style

Specifies how nested elements are rendered in 3D space

perspective

Specifies the perspective on how 3D elements are viewed

perspective-origin

Specifies the bottom position of 3D elements

backface-visibility

Defines whether or not an element should be visible when not facing the screen

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

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:

Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring

SHARE THIS PAGE

CSS3 Transitions
Previous
Next Chapter

CSS3 Transitions
CSS3 transitions allows you to change property values smoothly (from one
value to another), over a given duration.
Example: Mouse over the element below to see a CSS3 transition effect:
CSS3

Browser Support for Transitions

The numbers in the table specify the first browser version that fully supports the
property.
Numbers followed by -webkit-, -moz-, or -o- specify the first version that
worked with a prefix.

Property
transition

26.0
4.0 -webkit-

10.0

16.0
4.0 -moz-

6.1
3.1 -webkit-

transition-delay

26.0
4.0 -webkit-

10.0

16.0
4.0 -moz-

6.1
3.1 -webkit-

transition-duration

26.0
4.0 -webkit-

10.0

16.0
4.0 -moz-

6.1
3.1 -webkit-

transition-property

26.0
4.0 -webkit-

10.0

16.0
4.0 -moz-

6.1
3.1 -webkit-

transition-timing-function

26.0
4.0 -webkit-

10.0

16.0
4.0 -moz-

6.1
3.1 -webkit-

How to Use CSS3 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 <div> element. The <div>
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;
-webkit-transition: width 2s; /* Safari */
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 <div> element:

Example
div:hover {
width: 300px;
}
Try it Yourself
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 {
-webkit-transition: width 2s, height 4s; /* Safari */
transition: width 2s, height 4s;
}
Try it Yourself

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 the some of the different speed curves that can be
used:

Example
#div1
#div2
#div3
#div4
#div5

{transition-timing-function:
{transition-timing-function:
{transition-timing-function:
{transition-timing-function:
{transition-timing-function:

linear;}
ease;}
ease-in;}
ease-out;}
ease-in-out;}

Try it Yourself

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 {
-webkit-transition-delay: 1s; /* Safari */
transition-delay: 1s;
}
Try it Yourself

Transition + Transformation
The following example also adds a transformation to the transition effect:

Example
div {
-webkit-transition: width 2s, height 2s, -webkit-transform 2s; /* Safari */
transition: width 2s, height 2s, transform 2s;
}
Try it Yourself

More Transition Examples


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

Try it Yourself
or by using the shorthand property transition:

Example
div {
transition: width 2s linear 1s;
}
Try it Yourself

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4 Exercise 5

CSS3 Transition Properties


The following table lists all the transition properties:

Property

Description

transition

A shorthand property for setting the four transition properties into a single prop

transition-delay

Specifies a delay (in seconds) for the transition effect

transition-duration

Specifies how many seconds or milliseconds a transition effect takes to comple

transition-property

Specifies the name of the CSS property the transition effect is for

transition-timing-function

Specifies the speed curve of the transition effect

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:
Color Converter
Google Maps
Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring

SHARE THIS PAGE

CSS3 Animations
Previous

Next Chapter

CSS3 Animations
CSS3 animations allows animation of most HTML elements without using
JavaScript or Flash!

CSS3
Animation

Browser Support for Animations


The numbers in the table specify the first browser version that fully supports the
property.
Numbers followed by -webkit-, -moz-, or -o- specify the first version that
worked with a prefix.

Property
@keyframes

43.0
4.0 -webkit-

10.0

16.0
5.0 -moz-

9.0
4.0 -webkit-

animation

43.0
4.0 -webkit-

10.0

16.0
5.0 -moz-

9.0
4.0 -webkit-

What are CSS3 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 you want.
To use CSS3 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 <div> element.
The animation will lasts for 4 seconds, and it will gradually change the
background-color of the <div> 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;
}
Try it Yourself
Note: If the animation-duration property is not specified, the animation will
have no effect, because the default value is 0.
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 <div> 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;
}
Try it Yourself
The following example will change both the background-color and the position
of the <div> 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;
}
Try it Yourself

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;
}
Try it Yourself

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;
}
Try it Yourself
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;
}
Try it Yourself

Run Animation in Reverse Direction or


Alternate Cycles
The animation-direction property is used to let an animation run in reverse
direction or alternate cycles.
The following example will run the animation in reverse direction:

Example
div {
width: 100px;

height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-iteration-count: 3;
animation-direction: reverse;
}
Try it Yourself
The following example uses the value "alternate" to make the animation first
run forward, then backward, then forward:

Example
div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-iteration-count: 3;
animation-direction: alternate;
}
Try it Yourself

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 cubicbezier function

The following example shows the some of the different speed curves that can be
used:

Example
#div1
#div2
#div3
#div4
#div5

{animation-timing-function:
{animation-timing-function:
{animation-timing-function:
{animation-timing-function:
{animation-timing-function:

linear;}
ease;}
ease-in;}
ease-out;}
ease-in-out;}

Try it Yourself

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;
}
Try it Yourself
The same animation effect as above can be achieved by using the
shorthand animation property:

Example
div {
animation: example 5s linear 2s infinite alternate;
}
Try it Yourself

Test Yourself with Exercises!


Exercise 1 Exercise 2 Exercise 3 Exercise 4 Exercise 5 Exercise 6

CSS3 Animation Properties


The following table lists the @keyframes rule and all the animation properties:

Property

Description

@keyframes

Specifies the animation code

animation

A shorthand property for setting all the animation properties

animation-delay

Specifies a delay for the start of an animation

animation-direction

Specifies whether an animation should play in reverse directio


cycles

animation-duration

Specifies how many seconds or milliseconds an animation take

complete one cycle

animation-fill-mode

Specifies a style for the element when the animation is not pla
is finished, or when it has a delay)

animation-iteration-count

Specifies the number of times an animation should be played

animation-name

Specifies the name of the @keyframes animation

animation-play-state

Specifies whether the animation is running or paused

animation-timing-function

Specifies the speed curve of the animation

Previous
Next Chapter

CSS Images
Previous
Next Chapter

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

Try it Yourself

Example
Circled Image:
img {
border-radius: 50%;
}

Try it Yourself

Thumbnail Images
Use the border property to create thumbnail images.
Thumbnail Image:

Example
img {
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px;
}
<img src="paris.jpg" alt="Paris">

Try it Yourself
Thumbnail Image as Link:

Example
a{
display: inline-block;
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px;
transition: 0.3s;
}
a:hover {
box-shadow: 0 0 2px 1px rgba
(0, 140, 186, 0.5);
}
<a href="paris.jpg">
<img src="paris.jpg" alt="Paris">
</a>

Try it Yourself

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

Try it Yourself
Tip: Read more about Responsive Web Design in our CSS RWD Tutorial.

Image Text
How to position text in an image:

Example

Bottom Left
Top Left
Top Right
Bottom Right
Centered
Try it Yourself:
Top Left Top Right Bottom Left Bottom Right Centered

Polaroid Images / Cards

The Troll's tongue in Hardanger, Norway

Northern Lights in Norway

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

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, Edge 12, or
Safari 5.1 and earlier.

Example
Change the color of all images to black and white (100% gray):
img {
-webkit-filter: grayscale(100%); /* Chrome, Safari, Opera */
filter: grayscale(100%);
}

Try it Yourself
Tip: Go to our CSS filter Reference to learn more about CSS filters.

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:

Add a description of the image here

Add a description of the image here

Add a description of the image here

Add a description of the image here

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

Try it Yourself
Tip: Read more about Responsive Web Design in our CSS RWD Tutorial.

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;
modalImg.alt = this.alt;
captionText.innerHTML = this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}

Try it Yourself

Previous

Next Chapter

CSS Buttons
Previous
Next Chapter

Learn how to style buttons using CSS.

Basic Button Styling


Default Button CSS Button

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

Try it Yourself

Button Colors
Green Blue Red Gray Black

Use the background-color property to change the background color of a


button:

Example
.button1
.button2
.button3
.button4
.button5

{background-color:
{background-color:
{background-color:
{background-color:
{background-color:

#4CAF50;} /* Green */
#008CBA;} /* Blue */
#f44336;} /* Red */
#e7e7e7; color: black;} /* Gray */
#555555;} /* Black */

Try it Yourself

Button Sizes
10px 12px 16px 20px 24px
Use the font-size property to change the font size of a button:

Example
.button1
.button2
.button3
.button4
.button5

{font-size:
{font-size:
{font-size:
{font-size:
{font-size:

10px;}
12px;}
16px;}
20px;}
24px;}

Try it Yourself
Use the padding property to change the padding of a button:
10px 24px 12px 28px 14px 40px 32px 16px 16px

Example
.button1
.button2
.button3
.button4
.button5

{padding:
{padding:
{padding:
{padding:
{padding:

10px 24px;}
12px 28px;}
14px 40px;}
32px 16px;}
16px;}

Try it Yourself

Rounded Buttons
2px 4px 8px 12px 50%
Use the border-radius property to add rounded corners to a button:

Example
.button1
.button2
.button3
.button4
.button5

{border-radius:
{border-radius:
{border-radius:
{border-radius:
{border-radius:

2px;}
4px;}
8px;}
12px;}
50%;}

Try it Yourself

Colored Button Borders


Green Blue Red Gray Black
Use the border property to add a colored border to a button:

Example
.button1 {
background-color: white;
color: black;
border: 2px solid #4CAF50; /* Green */
}
...

Try it Yourself

Hoverable Buttons

Green Blue Red Grey Black


Green Blue Red Grey Black
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 {
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
}
.button:hover {
background-color: #4CAF50; /* Green */
color: white;
}
...

Try it Yourself

Shadow Buttons
Shadow Button Shadow on hover
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);
}

Try it Yourself

Disabled Buttons
Normal Button Disabled Button
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;
}

Try it Yourself

Button Width
250px
50% 100%
By default, the size of the button is determined by its text content (as wide as
its content). Use the widthproperty to change the width of a button:

Example
.button1 {width: 250px;}
.button2 {width: 50%;}
.button3 {width: 100%;}

Try it Yourself

Button Groups
ButtonButtonButtonButton
Remove margins and add float:left to each button to create a button group:

Example
.button {
float: left;
}

Try it Yourself

Bordered Button Groups


ButtonButtonButtonButton
Use the border property to create a bordered button group:

Example
.button {
float: left;
border: 1px solid green
}

Try it Yourself

Animated Buttons
Example
Add an arrow on hover:

Hover
Try it Yourself

Example
Add a "ripple" effect on click:
Click
Try it Yourself

Example
Add a "pressed" effect on click:
Click
Try it Yourself

Previous
Next Chapter
W3SCHOOLS EXAMS

HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications


COLOR PICKER

LEARN MORE:

Color Converter
Google Maps
Animated Buttons
Modal Boxes

Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring
SHARE THIS PAGE

CSS Pagination Examples


Previous

Next Chapter

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:

To create a pagination, style a HTML list:

Example
ul.pagination {
display: inline-block;
padding: 0;
margin: 0;
}
ul.pagination li {display: inline;}
ul.pagination li a {
color: black;
float: left;
padding: 8px 16px;
text-decoration: none;
}
Try it Yourself

Active and Hoverable Pagination

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
ul.pagination li a.active {
background-color: #4CAF50;
color: white;
}
ul.pagination li a:hover:not(.active) {background-color: #ddd;}
Try it Yourself

Rounded Active and Hoverable Buttons

Add the border-radius property if you want a rounded "active" and "hover"
button:

Example
ul.pagination li a {
border-radius: 5px;
}
ul.pagination li a.active {
border-radius: 5px;
}
Try it Yourself

Hoverable Transition Effect

Add the transition property to the page links to create a transition effect on
hover:

Example

ul.pagination li a {
transition: background-color .3s;
}
Try it Yourself

Bordered Pagination

Use the border property to add borders to the pagination:

Example
ul.pagination li a {
border: 1px solid #ddd; /* Gray */

}
Try it Yourself

Rounded Borders
Tip: Add rounded borders to your first and last link in the pagination:

Example
.pagination li:first-child a {
border-top-left-radius: 5px;
border-bottom-left-radius: 5px;
}
.pagination li:last-child a {

border-top-right-radius: 5px;
border-bottom-right-radius: 5px;
}
Try it Yourself

Space Between Links


Tip: Add the margin property if you do not want to group the page links:

Example
ul.pagination li a {
margin: 0 4px; /* 0 is for top and bottom. Feel free to change it */
}

Try it Yourself

Pagination Size

Change the size of the pagination with the font-size property:

Example
ul.pagination li a {
font-size: 22px;
}

Try it Yourself

Centered Pagination

To center the pagination, wrap a container element around it (like <div>), and
add text-align:center

Example
div.center {
text-align: center;
}
Try it Yourself

More Examples
Example
Try it Yourself

Breadcrumbs

Home

Pictures

Summer 15

Italy

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: "/\00a0";

}
Try it Yourself

Previous
Next Chapter

CSS3 Multiple Columns


Previous

Next Chapter

CSS3 Multi-column Layout


The CSS3 multi-column layout allows easy definition of multiple columns of text
- just like in newspapers:
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.

Browser Support
The numbers in the table specify the first browser version that fully supports the
property.

Numbers followed by -webkit- or -moz- specify the first version that worked
with a prefix.

Property
column-count

50.0
4.0 -webkit-

10.0

2.0 -moz-

9.0
3.1 -webkit-

column-gap

50.0
4.0 -webkit-

10.0

2.0 -moz-

9.0
3.1 -webkit-

column-rule

50.0
4.0 -webkit-

10.0

2.0 -moz-

9.0
3.1 -webkit-

column-rule-color

50.0
4.0 -webkit-

10.0

2.0 -moz-

9.0
3.1 -webkit-

column-rule-style

50.0
4.0 -webkit-

10.0

2.0 -moz-

9.0
3.1 -webkit-

column-rule-width

50.0
4.0 -webkit-

10.0

2.0 -moz-

9.0
3.1 -webkit-

column-width

50.0
4.0 -webkit-

10.0

2.0 -moz-

9.0
3.1 -webkit-

CSS3 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

CSS3 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 {
-webkit-column-count: 3; /* Chrome, Safari, Opera */
-moz-column-count: 3; /* Firefox */
column-count: 3;
}
Try it Yourself

CSS3 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 {
-webkit-column-gap: 40px; /* Chrome, Safari, Opera */
-moz-column-gap: 40px; /* Firefox */

column-gap: 40px;
}
Try it Yourself

CSS3 Column Rules


The column-rule-style property specifies the style of the rule between
columns:

Example
div {
-webkit-column-rule-style: solid; /* Chrome, Safari, Opera */
-moz-column-rule-style: solid; /* Firefox */
column-rule-style: solid;
}
Try it Yourself
The column-rule-width property specifies the width of the rule between
columns:

Example
div {
-webkit-column-rule-width: 1px; /* Chrome, Safari, Opera */
-moz-column-rule-width: 1px; /* Firefox */
column-rule-width: 1px;
}
Try it Yourself
The column-rule-color property specifies the color of the rule between
columns:

Example
div {
-webkit-column-rule-color: lightblue; /* Chrome, Safari, Opera */
-moz-column-rule-color: lightblue; /* Firefox */

column-rule-color: lightblue;
}
Try it Yourself
The column-rule property is a shorthand property for setting all the columnrule-* properties above.
The following example sets the width, style, and color of the rule between
columns:

Example
div {
-webkit-column-rule: 1px solid lightblue; /* Chrome, Safari, Opera */
-moz-column-rule: 1px solid lightblue; /* Firefox */
column-rule: 1px solid lightblue;
}
Try it Yourself

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 {
-webkit-column-span: all; /* Chrome, Safari, Opera */
column-span: all;
}
Try it Yourself

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 {
-webkit-column-width: 100px; /* Chrome, Safari, Opera */
column-width: 100px;
}
Try it Yourself

CSS3 Multi-columns Properties


The following table lists all the multi-columns properties:

Property

Description

column-count

Specifies the number of columns an element should be divided

column-fill

Specifies how to fill columns

column-gap

Specifies the gap between the columns

column-rule

A shorthand property for setting all the column-rule-* properti

column-rule-color

Specifies the color of the rule between columns

column-rule-style

Specifies the style of the rule between columns

column-rule-width

Specifies the width of the rule between columns

column-span

Specifies how many columns an element should span across

column-width

Specifies a suggested, optimal width for the columns

columns

A shorthand property for setting column-width and column-cou

Previous
Next Chapter

CSS3 User Interface


Previous

Next Chapter

CSS3 User Interface


CSS3 has new user interface features such as resizing elements, outlines, and
box sizing.
In this chapter you will learn about the following user interface properties:

resize

outline-offset

Browser Support
The numbers in the table specify the first browser version that fully supports the
property.
Numbers followed by -webkit- or -moz- specify the first version that worked
with a prefix.

Property
resize

4.0

Not supported

5.0
4.0 -moz-

4.0

outline-offset

4.0

Not supported

5.0
4.0 -moz-

4.0

CSS3 Resizing
The resize property specifies whether or not an element should be resizable by
the user.
This div element is resizable by the user (works in Chrome, Firefox, Safari and
Opera).
The following example lets the user resize only the width of a <div> element:

Example
div {
resize: horizontal;
overflow: auto;
}
Try it Yourself

The following example lets the user resize only the height of a <div> element:

Example
div {
resize: vertical;
overflow: auto;
}
Try it Yourself
The following example lets the user resize both the height and the width of a
<div> element:

Example
div {
resize: both;
overflow: auto;
}
Try it Yourself

CSS3 Outline Offset


The outline-offset property adds space between an outline and the edge or
border of an element.
Outlines differ from borders in three ways:

An outline is a line drawn around elements, outside the border edge

An outline does not take up space

An outline may be non-rectangular

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


The following example uses the outline-offset property to add a 15px space
between the border and the outline:

Example
div {
border: 1px solid black;
outline: 1px solid red;
outline-offset: 15px;
}
Try it Yourself

CSS3 User Interface Properties


The following table lists all the user interface properties:

Property

Description

box-sizing

Allows you to include the padding and border in an element's t


and height

nav-down

Specifies where to navigate when using the arrow-down navig

nav-index

Specifies the tabbing order for an element

nav-left

Specifies where to navigate when using the arrow-left navigati

nav-right

Specifies where to navigate when using the arrow-right naviga

nav-up

Specifies where to navigate when using the arrow-up navigatio

outline-offset

Adds space between an outline and the edge or border of an e

resize

Specifies whether or not an element is resizable by the user

Previous
Next Chapter

CSS3 Box Sizing


Previous
Next Chapter

CSS3 Box Sizing


The CSS3 box-sizing property allows us to include the padding and border in an
element's total width and height.

Browser Support
The numbers in the table specify the first browser version that fully supports the
property.
Numbers followed by -webkit- or -moz- specify the first version that worked
with a prefix.
Property
box-sizing

10.0

8.0

29.0

5.1

4.0 -webkit-

2.0 -moz-

3.1 -webkit-

Without the CSS3 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
appear 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 <div> 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 <div> 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;


}

Try it Yourself
So, for a long time web developers have specified a smaller width value than
they wanted, because they had to subtract out the padding and borders.
With CSS3, the box-sizing property solves this problem.

With the CSS3 box-sizing Property


The CSS3 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
<div> 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;
}

Try it Yourself
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;
}

Try it Yourself

Previous
Next Chapter

CSS3 Flexible Box


Previous
Next Chapter

CSS3 Flexbox
Flexible boxes, or flexbox, is a new layout mode in CSS3.

Use of flexbox ensures that elements behave predictably when the page layout must
accommodate different screen sizes and different display devices.
For many applications, the flexible box model provides an improvement over the block model in
that it does not use floats, nor do the flex container's margins collapse with the margins of its
contents.

Browser Support
The numbers in the table specify the first browser version that fully supports the feature.
Numbers followed by -webkit- or -moz- specify the first version that worked with a prefix.
Property
Basic support
(single-line flexbox)

29.0
21.0 -webkit-

11.0

22.0
18.0 -moz-

6.1 -webkit-

Multi-line flexbox

29.0
21.0 -webkit-

11.0

28.0

6.1 -webkit-

CSS3 Flexbox Concepts


Flexbox consists of flex containers and flex items.
A flex container is declared by setting the display property of an element to
either flex (rendered as a block) or inline-flex (rendered as inline).
Inside a flex container there is one or more flex items.
Note: Everything outside a flex container and inside a flex item is rendered as usual. Flexbox
defines how flex items are laid out inside a flex container.
Flex items are positioned inside a flex container along a flex line. By default there is only one
flex line per flex container.
The following example shows three flex items. They are positioned by default: along the
horizontal flex line, from left to right:

Example
<!DOCTYPE html>
<html>
<head>
<style>
.flex-container {
display: -webkit-flex;
display: flex;
width: 400px;
height: 250px;
background-color: lightgrey;
}
.flex-item {
background-color: cornflowerblue;
width: 100px;
height: 100px;
margin: 10px;
}
</style>
</head>
<body>
<div class="flex-container">
<div class="flex-item">flex item 1</div>
<div class="flex-item">flex item 2</div>
<div class="flex-item">flex item 3</div>
</div>
</body>
</html>
Try it Yourself
It is also possible to change the direction of the flex line.
If we set the direction property to rtl (right-to-left), the text is drawn right to left, and also the
flex line changes direction, which will change the page layout:

Example
body {
direction: rtl;
}

.flex-container {
display: -webkit-flex;
display: flex;
width: 400px;
height: 250px;
background-color: lightgrey;
}
.flex-item {
background-color: cornflowerblue;
width: 100px;
height: 100px;
margin: 10px;
}
Try it Yourself

Flex Direction
The flex-direction property specifies the direction of the flexible items inside the flex
container. The default value of flex-direction is row (left-to-right, top-to-bottom).
The other values are as follows:

row-reverse

column

column-reverse

- If the writing-mode (direction) is left to right, the flex items will be laid
out right to left
- If the writing system is horizontal, the flex items will be laid out vertically
- Same as column, but reversed

The following example shows the result of using the row-reverse value:

Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: row-reverse;
flex-direction: row-reverse;
width: 400px;
height: 250px;

background-color: lightgrey;
}
Try it Yourself
The following example shows the result of using the column value:

Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: column;
flex-direction: column;
width: 400px;
height: 250px;
background-color: lightgrey;
}
Try it Yourself
The following example shows the result of using the column-reverse value:

Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: column-reverse;
flex-direction: column-reverse;
width: 400px;
height: 250px;
background-color: lightgrey;
}
Try it Yourself

The justify-content Property


The justify-content property horizontally aligns the flexible container's items when the items
do not use all available space on the main-axis.
The possible values are as follows:

flex-start

flex-end

center

space-between

space-around

- Default value. Items are positioned at the beginning of the container

- Items are positioned at the end of the container

- Items are positioned at the center of the container


- Items are positioned with space between the lines

- Items are positioned with space before, between, and after the lines

The following example shows the result of using the flex-end value:

Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-justify-content: flex-end;
justify-content: flex-end;
width: 400px;
height: 250px;
background-color: lightgrey;
}
Try it Yourself
The following example shows the result of using the center value:

Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-justify-content: center;
justify-content: center;
width: 400px;
height: 250px;
background-color: lightgrey;
}
Try it Yourself
The following example shows the result of using the space-between value:

Example

.flex-container {
display: -webkit-flex;
display: flex;
-webkit-justify-content: space-between;
justify-content: space-between;
width: 400px;
height: 250px;
background-color: lightgrey;
}
Try it Yourself
The following example shows the result of using the space-around value:

Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-justify-content: space-around;
justify-content: space-around;
width: 400px;
height: 250px;
background-color: lightgrey;
}
Try it Yourself

The align-items Property


The align-items property vertically aligns the flexible container's items when the items do not
use all available space on the cross-axis.
The possible values are as follows:

stretch

flex-start

flex-end

center

- Default value. Items are stretched to fit the container


- Items are positioned at the top of the container

- Items are positioned at the bottom of the container

- Items are positioned at the center of the container (vertically)

baseline

- Items are positioned at the baseline of the container

The following example shows the result of using the stretch value (this is the default value):

Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-align-items: stretch;
align-items: stretch;
width: 400px;
height: 250px;
background-color: lightgrey;
}
Try it Yourself
The following example shows the result of using the flex-start value:

Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-align-items: flex-start;
align-items: flex-start;
width: 400px;
height: 250px;
background-color: lightgrey;
}
Try it Yourself
The following example shows the result of using the flex-end value:

Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-align-items: flex-end;
align-items: flex-end;
width: 400px;
height: 250px;

background-color: lightgrey;
}
Try it Yourself
The following example shows the result of using the center value:

Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-align-items: center;
align-items: center;
width: 400px;
height: 250px;
background-color: lightgrey;
}
Try it Yourself
The following example shows the result of using the baseline value:

Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-align-items: baseline;
align-items: baseline;
width: 400px;
height: 250px;
background-color: lightgrey;
}
Try it Yourself

The flex-wrap Property


The flex-wrap property specifies whether the flex items should wrap or not, if there is not
enough room for them on one flex line.
The possible values are as follows:

nowrap

wrap

wrap-reverse

- Default value. The flexible items will not wrap

- The flexible items will wrap if necessary


- The flexible items will wrap, if necessary, in reverse order

The following example shows the result of using the nowrap value (this is the default value):

Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-wrap: nowrap;
flex-wrap: nowrap;
width: 300px;
height: 250px;
background-color: lightgrey;
}
Try it Yourself
The following example shows the result of using the wrap value:

Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-wrap: wrap;
flex-wrap: wrap;
width: 300px;
height: 250px;
background-color: lightgrey;
}
Try it Yourself
The following example shows the result of using the wrap-reverse value:

Example
.flex-container {
display: -webkit-flex;
display: flex;

-webkit-flex-wrap: wrap-reverse;
flex-wrap: wrap-reverse;
width: 300px;
height: 250px;
background-color: lightgrey;
}
Try it Yourself

The align-content Property


The align-content property modifies the behavior of the flex-wrap property. It is similar
to align-items, but instead of aligning flex items, it aligns flex lines.
The possible values are as follows:

stretch

flex-start

flex-end

center

space-between

space-around

- Default value. Lines stretch to take up the remaining space


- Lines are packed toward the start of the flex container

- Lines are packed toward the end of the flex container

- Lines are packed toward the center of the flex container


- Lines are evenly distributed in the flex container

- Lines are evenly distributed in the flex container, with half-size spaces

on either end
The following example shows the result of using the center value:

Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-wrap: wrap;
flex-wrap: wrap;
-webkit-align-content: center;
align-content: center;
width: 300px;
height: 300px;

background-color: lightgrey;
}
Try it Yourself

Flex Item Properties


Ordering
The order property specifies the order of a flexible item relative to the rest of the flexible items
inside the same container:

Example
.flex-item {
background-color: cornflowerblue;
width: 100px;
height: 100px;
margin: 10px;
}
.first {
-webkit-order: -1;
order: -1;
}
Try it Yourself

Margin
Setting margin: auto; will absorb extra space. It can be used to push flex items into different
positions.
In the following example we set margin-right: auto; on the first flex item. This will cause all
the extra space to be absorbed to the right of that element:

Example
.flex-item {
background-color: cornflowerblue;
width: 75px;
height: 75px;

margin: 10px;
}
.flex-item:first-child {
margin-right: auto;
}
Try it Yourself

Perfect Centering
In the following example we will solve an almost daily problem: perfect centering.
It is very easy with flexbox. Setting margin: auto; will make the item perfectly centered in
both axis:

Example
.flex-item {
background-color: cornflowerblue;
width: 75px;
height: 75px;
margin: auto;
}
Try it Yourself

align-self
The align-self property of flex items overrides the flex container's align-items property for
that item. It has the same possible values as the align-items property.
The following example sets different align-self values to each flex item:

Example
.flex-item {
background-color: cornflowerblue;
width: 60px;
min-height: 100px;
margin: 10px;
}
.item1 {
-webkit-align-self: flex-start;

align-self: flex-start;
}
.item2 {
-webkit-align-self: flex-end;
align-self: flex-end;
}
.item3 {
-webkit-align-self: center;
align-self: center;
}
.item4 {
-webkit-align-self: baseline;
align-self: baseline;
}
.item5 {
-webkit-align-self: stretch;
align-self: stretch;
}
Try it Yourself

flex
The flex property specifies the length of the flex item, relative to the rest of the flex items inside
the same container.
In the following example, the first flex item will consume 2/4 of the free space, and the other two
flex items will consume 1/4 of the free space each:

Example
.flex-item {
background-color: cornflowerblue;
margin: 10px;
}
.item1 {
-webkit-flex: 2;
flex: 2;
}
.item2 {

-webkit-flex: 1;
flex: 1;
}
.item3 {
-webkit-flex: 1;
flex: 1;
}
Try it Yourself

More Examples
Create a responsive website with flexbox
This example demonstrates how to create a responsive website layout with flexbox.

CSS3 Flexbox Properties


The following table lists the CSS properties used with flexbox:

Property

Description

display

Specifies the type of box used for an HTML element

flex-direction

Specifies the direction of the flexible items inside a flex container

justify-content

Horizontally aligns the flex items when the items do not use all available space
axis

align-items

Vertically aligns the flex items when the items do not use all available space on

flex-wrap

Specifies whether the flex items should wrap or not, if there is not enough room
one flex line

align-content

Modifies the behavior of the flex-wrap property. It is similar to align-items, but


aligning flex items, it aligns flex lines

flex-flow

A shorthand propert for flex-direction and flex-wrap

order

Specifies the order of a flexible item relative to the rest of the flex items inside
container

align-self

Used on flex items. Overrides the container's align-items property

flex

Specifies the length of a flex item, relative to the rest of the flex items inside th
container

Previous
Next Chapter
W3SCHOOLS EXAMS
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML Certifications

COLOR PICKER

LEARN MORE:
Color Converter
Google Maps

Animated Buttons
Modal Boxes
Modal Images
Tooltips
Loaders
JS Animations
Progress Bars
Dropdowns
Slideshow
Side Navigation
HTML Includes
Color Palettes
Code Coloring

SHARE THIS PAGE

CSS3 Media Queries


Previous
Next Chapter

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 Introduces Media Queries

Media queries in CSS3 extend 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 tablets, iPhone, and Androids.

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

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

4.0

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:

<link rel="stylesheet" media="mediatype and|not|only (expressions)"


href="print.css">

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;
}
}
Try it Yourself
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;}
}
Try it Yourself

CSS3 @media Reference


For a full overview of all the media types and features/expressions, please look
at the @media rule in our CSS reference.

CSS3 Media Queries - Examples

Previous
Next Chapter

CSS3 Media Queries - More Examples


Let us look at some more examples of using media queries.
We will start with a list of names which function as email links. The HTML is:

Example 1
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
}
ul li a {
color: green;
text-decoration: none;
padding: 3px;
display: block;
}
</style>
</head>
<body>
<ul>
<li><a data-email="johndoe@example.com" hre
f="mailto:johndoe@example.com">John Doe</a></li>
<li><a data-email="marymoe@example.com" hre
f="mailto:marymoe@example.com">Mary Moe</a></li>
<li><a dataemail="amandapanda@example.com"href="mailto:amandapanda@example.com">
Amanda Panda</a></li>
</ul>
</body>
</html>

Try it Yourself
Notice the data-email attribute. In HTML5, we can use attributes prefixed
with data- to store information. We will use the data- attribute later.

Width from 520 to 699px - Apply an


email icon to each link
When the browser's width is between 520 and 699px, we will apply an email
icon to each email link:

Example 2
@media screen and (max-width: 699px) and (min-width: 520px) {
ul li a {
padding-left: 30px;
background: url(email-icon.png) left center no-repeat;
}
}

Try it Yourself

Width from 700 to 1000px - Preface the


links with a text
When the browser's width is between from 700 to 1000px, we will preface each
email link with the text "Email: ":

Example 3
@media screen and (max-width: 1000px) and (min-width: 700px) {
ul li a:before {
content: "Email: ";
font-style: italic;
color: #666666;

}
}

Try it Yourself

Width above 1001px - Apply email


address to links
When the browser's width is above 1001px, we will append the email address to
the links.
We will use the value of the data- attribute to add the email address after the
person's name:

Example 4
@media screen and (min-width: 1001px) {
ul li a:after {
content: " (" attr(data-email) ")";
font-size: 12px;
font-style: italic;
color: #666666;
}
}

Try it Yourself

Width above 1151px - Add icon as we


used before
For browser widths above 1151px, we will again add the icon as we used before.

Here, we do not have to write an additional media query block, we can just
append an additional media query to our already existing one using a comma
(this will behave like an OR operator):

Example 5
@media screen and (max-width: 699px) and (min-width: 520px), (min-width:
1151px) {
ul li a {
padding-left: 30px;
background: url(email-icon.png) left center no-repeat;
}
}

Try it Yourself

More Examples
Use the list of email links on a sidebar in a web page
This example puts the list of email links into the left sidebar of a webpage.

Previous
Next Chapter

Você também pode gostar