0% found this document useful (0 votes)
6 views

CSS Notes

CSS (Cascading Style Sheets) is a language used to style and lay out web pages. CSS allows you to control the color, font, size, spacing and layout of text, images, and other HTML elements. CSS saves a lot of work by allowing the formatting of multiple web pages from a single external CSS file. The document then demonstrates how one HTML page can be styled differently using four different external CSS style sheets.

Uploaded by

Eishal Zahra
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

CSS Notes

CSS (Cascading Style Sheets) is a language used to style and lay out web pages. CSS allows you to control the color, font, size, spacing and layout of text, images, and other HTML elements. CSS saves a lot of work by allowing the formatting of multiple web pages from a single external CSS file. The document then demonstrates how one HTML page can be styled differently using four different external CSS style sheets.

Uploaded by

Eishal Zahra
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

CSS Introduction

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

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

CSS Demo - One HTML Page -


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

Welcome to My Homepage
Use the menu to select different Stylesheets
 Stylesheet 1
 Stylesheet 2
 Stylesheet 3
 Stylesheet 4
 No Stylesheet
Same Page
Different
Stylesheets
This is a
demonstration of
how different
stylesheets can
change the layout of
your HTML page.
You can change the
layout of this page
by selecting
different stylesheets
in the menu, or by
selecting one of the
following links:
Stylesheet1, Stylesh
eet2, Stylesheet3, St
ylesheet4.
No Styles
This page uses DIV
elements to group
different sections of
the HTML page.
Click here to see
how the page looks
like with no
stylesheet:
No Stylesheet.
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.

Why Use CSS?


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

CSS Example

body {
background-color: lightblue;
}

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

p {
font-family: verdana;
font-size: 20px;
}
CSS Solved a Big Problem
HTML was NEVER intended to contain tags for formatting a web page!

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

<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
A CSS rule consists of a selector and a declaration block.

CSS Syntax

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

The declaration block contains one or more declarations separated by


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

Multiple CSS declarations are separated with semicolons, and declaration


blocks are surrounded by curly braces.

Example

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

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

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

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

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

We can divide CSS selectors into five categories:

 Simple selectors (select elements based on name, id, class)


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

This page will explain the most basic CSS selectors.


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

Example

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

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

The CSS id Selector


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

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


select one unique element!

To select an element with a specific id, write a hash (#) character,


followed by the id of the element.

Example

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

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

Note: An id name cannot start with a number!

The CSS class Selector


The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character,
followed by the class name.

Example

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

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

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

Example

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

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

HTML elements can also refer to more than one class.

Example

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

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

Note: A class name cannot start with a number!


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

Example

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

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

The CSS Grouping Selector


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

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

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

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

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

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

To group selectors, separate each selector with a comma.

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

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

All CSS Simple Selectors


Selector Example Example description

#id #firstname Selects the element with id="firstname"

.class .intro Selects all elements with class="intro"

element.class p.intro Selects only <p> elements with class="in

* * Selects all elements

element p Selects all <p> elements

element,element,.. div, p Selects all <div> elements and all <p> e

How To Add CSS


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

Three Ways to Insert CSS


There are three ways of inserting a style sheet:

 External CSS
 Internal CSS
 Inline CSS

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

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

Example

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

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

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

</body>
</html>

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

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

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

"mystyle.css"

body {
background-color: lightblue;
}

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

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

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

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

Example

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

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

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

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

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

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

Example

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

<!DOCTYPE html>
<html>
<body>

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


<p style="color:red;">This is a paragraph.</p>

</body>
</html>

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

Multiple Style Sheets


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

Assume that an external style sheet has the following style for the <h1>
element:
h1 {
color: navy;
}

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

h1 {
color: orange;
}

Example

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

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

Example

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

<head>
<style>
h1 {
color: orange;
}
</style>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
Cascading Order
What style will be used when there is more than one style specified for an
HTML element?

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

1. Inline style (inside an HTML element)


2. External and internal style sheets (in the head section)
3. Browser default

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

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

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

Comments are ignored by browsers.

A CSS comment is placed inside the <style> element, and starts


with /* and ends with */:

Example

/* This is a single-line comment */


p {
color: red;
}

You can add comments wherever you want in the code:

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

Comments can also span multiple lines:

Example

/* This is
a multi-line
comment */

p {
color: red;
}

HTML and CSS Comments


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

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


comments:

Example

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

<h2>My Heading</h2>

<!-- These paragraphs will be red -->


<p>Hello World!</p>
<p>This paragraph is styled with CSS.</p>
<p>CSS comments are not shown in the output.</p>
</body>
</html>

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

CSS Color Names


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

Tomato

Orange

DodgerBlue

MediumSeaGreen

Gray

SlateBlue

Violet
LightGray

CSS/HTML support 140 standard color names.

CSS Background Color


You can set the background color for HTML elements:

Hello World

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

Example

<h1 style="background-color:DodgerBlue;">Hello World</h1>


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

CSS Text Color


You can set the color of text:

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

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper


suscipit lobortis nisl ut aliquip ex ea commodo consequat.

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

CSS Border Color


You can set the color of borders:

Hello World
Hello World
Hello World

Example

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


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

CSS Color Values


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

Same as color name "Tomato":

rgb(255, 99, 71)

#ff6347

hsl(9, 100%, 64%)


Same as color name "Tomato", but 50% transparent:
Example
<h1 style="background-color:rgb(255, 99, 71);">...</h1>
<h1 style="background-color:#ff6347;">...</h1>
<h1 style="background-color:hsl(9, 100%, 64%);">...</h1>

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


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

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

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

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

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

Example

The background color of a page is set like this:

body {
background-color: lightblue;
}

With CSS, a color is most often specified by:


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

Look at CSS Color Values for a complete list of possible color values.

Other Elements
You can set the background color for any HTML elements:

Example

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

h1 {
background-color: green;
}

div {
background-color: lightblue;
}

p {
background-color: yellow;
}

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

opacity 1

opacity 0.6

opacity 0.3

opacity 0.1

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

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

Transparency using RGBA


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

100% opacity

60% opacity

30% opacity

10% opacity

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

An RGBA color value is specified with: rgba(red, green, blue, alpha).


The alpha parameter is a number between 0.0 (fully transparent) and 1.0
(fully opaque).

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

Example

div {
background: rgba(0, 128, 0, 0.3) /* Green background with 30% opacity
*/
}
The CSS Background Color Property
Property Description

background-color Sets the background color of an element

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

I have borders on all sides.

I have a red bottom border.

I have rounded borders.

I have a blue left border.

CSS Border Style


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

The following values are allowed:

 dotted - Defines a dotted border


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

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

Example

Demonstration of the different border styles:

p.dotted {border-style: dotted;}


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

Result:

A dotted border.

A dashed border.

A solid border.

A double border.

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

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


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

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

No border.

A hidden border.

A mixed border.

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

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

This element has a margin of 70px.

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

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

Margin - Individual Sides


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

 margin-top
 margin-right
 margin-bottom
 margin-left

All the margin properties can have the following values:

 auto - the browser calculates the margin


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

Tip: Negative values are allowed.

Example

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

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

Margin - Shorthand Property


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

The margin property is a shorthand property for the following individual


margin properties:

 margin-top
 margin-right
 margin-bottom
 margin-left

So, here is how it works:

If the margin property has four values:

 margin: 25px 50px 75px 100px;


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

Example

Use the margin shorthand property with four values:

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

If the margin property has three values:

 margin: 25px 50px 75px;


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

Example

Use the margin shorthand property with three values:

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

If the margin property has two values:

 margin: 25px 50px;


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

Example

Use the margin shorthand property with two values:


p {
margin: 25px 50px;
}

If the margin property has one value:

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

Example

Use the margin shorthand property with one value:

p {
margin: 25px;
}

Try it Yourself »

The auto Value


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

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

Example

Use margin: auto:

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

The inherit Value


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

Example

Use of the inherit value:

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

p.ex1 {
margin-left: inherit;
}

All CSS Margin Properties


Property Description

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

margin-bottom Sets the bottom margin of an element

margin-left Sets the left margin of an element

margin-right Sets the right margin of an element

margin-top Sets the top margin of an element

CSS Padding
Padding is used to create space around an element's content, inside
of any defined borders.
This element has a padding of 70px.

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

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

Padding - Individual Sides


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

 padding-top
 padding-right
 padding-bottom
 padding-left

All the padding properties can have the following values:

 length - specifies a padding in px, pt, cm, etc.


 % - specifies a padding in % of the width of the containing element
 inherit - specifies that the padding should be inherited from the
parent element

Note: Negative values are not allowed.

Example

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

div {
padding-top: 50px;
padding-right: 30px;
padding-bottom: 50px;
padding-left: 80px;
}
Padding - Shorthand Property
To shorten the code, it is possible to specify all the padding properties in
one property.

The padding property is a shorthand property for the following individual


padding properties:

 padding-top
 padding-right
 padding-bottom
 padding-left

So, here is how it works:

If the padding property has four values:

 padding: 25px 50px 75px 100px;


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

Example

Use the padding shorthand property with four values:

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

If the padding property has three values:

 padding: 25px 50px 75px;


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

Example

Use the padding shorthand property with three values:


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

If the padding property has two values:

 padding: 25px 50px;


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

Example

Use the padding shorthand property with two values:

div {
padding: 25px 50px;
}

If the padding property has one value:

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

Example

Use the padding shorthand property with one value:

div {
padding: 25px;
}

Padding and Element Width


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

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

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

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

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

Example

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

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

More Examples
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.
All CSS Padding Properties
Property Description

padding A shorthand property for setting all the padding properties in

padding-bottom Sets the bottom padding of an element

padding-left Sets the left padding of an element

padding-right Sets the right padding of an element

padding-top Sets the top padding of an element

CSS Height, Width and


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

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


an element.

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

CSS Setting height and width


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

The height and width properties do not include padding, borders, or


margins. It sets the height/width of the area inside the padding, border,
and margin of the element.

CSS height and width Values


The height and width properties may have the following values:

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

CSS height and width Examples


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

Example

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

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

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

Example

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

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

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

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

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

Using max-width instead, in this situation, will improve the browser's


handling of small windows.

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

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

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

Example

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

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

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.

All CSS Dimension Properties


Property Description

height Sets the height of an element

max-height Sets the maximum height of an element

max-width Sets the maximum width of an element

min-height Sets the minimum height of an element

min-width Sets the minimum width of an element

width Sets the width of an element

CSS Box Model


All HTML elements can be considered as boxes.

The CSS Box Model


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

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

Explanation of the different parts:

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

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

Example
Demonstration of the box model:

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

Width and Height of an Element


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

Important: When you set the width and height properties of an element with
CSS, you just set the width and height of the content area. To calculate the full
size of an element, you must also add padding, borders and margins.

Example

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

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

Here is the calculation:

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

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

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

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


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

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

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

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

CSS has the following outline properties:

 outline-style
 outline-color
 outline-width
 outline-offset
 outline

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

CSS Outline Style


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

 dotted - Defines a dotted outline


 dashed - Defines a dashed outline
 solid - Defines a solid outline
 double - Defines a double outline
 groove - Defines a 3D grooved outline
 ridge - Defines a 3D ridged outline
 inset - Defines a 3D inset outline
 outset - Defines a 3D outset outline
 none - Defines no outline
 hidden - Defines a hidden outline
The following example shows the different outline-style values:

Example

Demonstration of the different outline styles:

p.dotted {outline-style: dotted;}


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

Result:

A dotted outline.

A dashed outline.

A solid outline.

A double outline.

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

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

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

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

Note: None of the other outline properties (which you will learn more about in the
next chapters) will have ANY effect unless the outline-style property is set!
CSS Text
CSS has a lot of properties for formatting text.

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

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

 a color name - like "red"


 a HEX value - like "#ff0000"
 an RGB value - like "rgb(255,0,0)"

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

Text Color and Background Color


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

Example

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

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

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

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

The CSS Text Color Property


Property Description

color Specifies the color of text

CSS Fonts
Choosing the right font for your website is important!

Font Selection is Important


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

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

Generic Font Families


In CSS there are five generic font families:

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

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

Difference Between Serif and Sans-


serif Fonts

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

Some Font Examples


Generic Font Family Examples of Font Names

Serif Times New Roman


Georgia
Garamond
Sans-serif Arial
Verdana
Helvetica
Monospace Courier New
Lucida Console
Monaco
Cursive Brush Script MT
Lucida Handwriting
Fantasy Copperplate
Papyrus

The CSS font-family Property


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

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

Tip: The font-family property should hold several font names as a


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

Example
Specify some different fonts for three paragraphs:

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

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

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

CSS Icons

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

How To Add Icons


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

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

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

Font Awesome Icons


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

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

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

Note: No downloading or installation is required!


Example

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

<i class="fas fa-cloud"></i>


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

</body>
</html>

Result:

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

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

<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstr
ap.min.css">

Note: No downloading or installation is required!

Example

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/
3.3.7/css/bootstrap.min.css">
</head>
<body>
<i class="glyphicon glyphicon-cloud"></i>
<i class="glyphicon glyphicon-remove"></i>
<i class="glyphicon glyphicon-user"></i>
<i class="glyphicon glyphicon-envelope"></i>
<i class="glyphicon glyphicon-thumbs-up"></i>

</body>
</html>

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

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?


family=Material+Icons">

Note: No downloading or installation is required!

Example

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?
family=Material+Icons">
</head>
<body>

<i class="material-icons">cloud</i>
<i class="material-icons">favorite</i>
<i class="material-icons">attachment</i>
<i class="material-icons">computer</i>
<i class="material-icons">traffic</i>

</body>
</html>

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

Text Link Text Link Link Button Link Button

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

Example

a {
color: hotpink;
}

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


are in.

The four links states are:

 a:link - a normal, unvisited link


 a:visited - a link the user has visited
 a:hover - a link when the user mouses over it
 a:active - a link the moment it is clicked

Example

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

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

/* mouse over link */


a:hover {
color: hotpink;
}

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

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

 a:hover MUST come after a:link and a:visited


 a:active MUST come after a:hover

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

Example

a:link {
text-decoration: none;
}

a:visited {
text-decoration: none;
}

a:hover {
text-decoration: underline;
}

a:active {
text-decoration: underline;
}

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

Example
a:link {
background-color: yellow;
}

a:visited {
background-color: cyan;
}

a:hover {
background-color: lightgreen;
}

a:active {
background-color: hotpink;
}

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

Example

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

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

CSS Lists

Unordered Lists:
o Coffee
o Tea
o Coca Cola
 Coffee
 Tea
 Coca Cola

Ordered Lists:
1. Coffee
2. Tea
3. Coca Cola
I. Coffee
II. Tea
III. Coca Cola

HTML Lists and CSS List Properties


In HTML, there are two main types of lists:

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

The CSS list properties allow you to:

 Set different list item markers for ordered lists


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

Different List Item Markers


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

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

Example

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

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

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

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

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

An Image as The List Item Marker


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

Example

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

Position The List Item Markers


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

"list-style-position: outside;" means that the bullet points will be outside


the list item. The start of each line of a list item will be aligned vertically.
This is default:

 Coffee - A brewed drink prepared from roasted coffee beans...


 Tea
 Coca-cola

"list-style-position: inside;" means that the bullet points will be inside the
list item. As it is part of the list item, it will be part of the text and push
the text at the start:
 Coffee - A brewed drink prepared from roasted coffee beans...
 Tea
 Coca-cola

Example

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

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

Remove Default Settings


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

Example

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

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

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

 list-style-type (if a list-style-image is specified, the value of this


property will be displayed if the image for some reason cannot be
displayed)
 list-style-position (specifies whether the list-item markers
should appear inside or outside the content flow)
 list-style-image (specifies an image as the list item marker)

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

Styling List With Colors


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

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

Example

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

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

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

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

Result:

1. Coffee

2. Tea

3. Coca Cola

 Coffee
 Tea
 Coca Cola

Try it Yourself »

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

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.

More Examples

Example

This example demonstrates how to add other styles to hyperlinks:

a.one:link {color: #ff0000;}


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

a.three:link {color: #ff0000;}


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

a.four:link {color: #ff0000;}


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

a.five:link {color: #ff0000; text-decoration: none;}


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

Example

Another example of how to create link boxes/buttons:

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

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

Example

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

<span style="cursor: auto">auto</span><br>


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

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

Company Contact

Alfreds Futterkiste Maria Anders

Berglunds snabbköp Christina Berglund

Centro comercial Moctezuma Francisco Chang

Ernst Handel Roland Mendel

Island Trading Helen Bennett

Königlich Essen Philip Cramer

Laughing Bacchus Winecellars Yoshi Tannamuri

Magazzini Alimentari Riuniti Giovanni Rovelli

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

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

Firstname Lastname
Peter Griffin
Lois Griffin
Example

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

Full-Width Table
Firstname
Peter
Lois

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

Example

table {
width: 100%;
}

Double Borders

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

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

Collapse Table Borders

Firstname
Peter
Lois

The border-collapse property sets whether the table borders should be


collapsed into a single border:
Example

table {
border-collapse: collapse;
}

Firstname Lastname
Peter Griffin
Lois Griffin

If you only want a border around the table, only specify


the border property for <table>:

Example

table {
border: 1px solid;
}

CSS Layout - The


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

The display Property


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

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

Click to show panel


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

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

Examples of block-level elements:

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

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

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

Examples of inline elements:

 <span>
 <a>
 <img>

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

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


Override The Default Display Value
As mentioned, every element has a default display value. However, you
can override this.

Changing an inline element to a block element, or vice versa, can be


useful for making the page look a specific way, and still follow the web
standards.

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

Example

li {
display: inline;
}

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

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

Example

span {
display: block;
}

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

Example

a {
display: block;
}
Hide an Element - display:none or
visibility:hidden?
display:none

Remove

visibility:hidden

Hide

Reset

Reset All

Hiding an element can be done by setting the display property to none.


The element will be hidden, and the page will be displayed as if the
element is not there:

Example

h1.hidden {
display: none;
}

visibility:hidden; also hides an element.

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

Example
h1.hidden {
visibility: hidden;
}

More Examples
Differences between display: none; and 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.

Property Description

display Specifies how an element should be displayed

visibility Specifies whether or not an element should be visible

CSS Display/Visibility Properties

You might also like