CAll Us: +232-79-006-790 Live Chat   Login

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

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:
Stylesheet1Stylesheet2Stylesheet3Stylesheet4.

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

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

Try it Yourself »

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!

I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

CSS Syntax

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

CSS Syntax

CSS selector

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

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

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

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

Example

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

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:

This page will explain the most basic CSS selectors.


The CSS element Selector

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

Example

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

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

The CSS id Selector

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

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

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

Example

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

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

Note: An id name cannot start with a number!

The CSS class Selector

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

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

Example

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

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

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

Example

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

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

The CSS Universal Selector

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

Example

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

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

The CSS Grouping Selector

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

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

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

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

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

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

To group selectors, separate each selector with a comma.

Example

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

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

Exercise:

Set the text color of all <p> elements to red.

<style>
 {
   red;
}
</style>

All CSS Simple Selectors

Selector Example Example description
#id #firstname Selects the element with id=”firstname”
.class .intro Selects all elements with class=”intro”
element.class p.intro Selects only <p> elements with class=”intro”
* * Selects all elements
element p Selects all <p> elements
element,element,.. div, p Selects all <div> elements and all <p> elements

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

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

Internal CSS

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

The internal style is defined inside the <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>

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

I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

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

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.

 

Exercise:

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

<head>

</head>

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

CSS Comments

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


CSS Comments

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

Comments are ignored by browsers.

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

Example

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

You can add comments wherever you want in the code:

Example

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

Even in the middle of a code line:

Example

{
color: /*red*/blue;
}

Comments can also span multiple lines:

Example

/* This is
a multi-line
comment */

{
color: red;
}

HTML and CSS Comments

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

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

Example

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

<h2>My Heading</h2>

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

</body>
</html>

Country codes can also be added to the language code in the lang attribute. So, the first two characters define the language of the HTML page, and the last two characters define the country.

The following example specifies English as the language and United States as the country:

<!DOCTYPE html>
<html lang=”en-US”>
<body>

</body>
</html>

You can see all the language codes in our HTML Language Code Reference.


The title Attribute

The title attribute defines some extra information about an element.

The value of the title attribute will be displayed as a tooltip when you mouse over the element:

Example

<p title=”I’m a tooltip”>This is a paragraph.</p>

We Suggest: Always Use Lowercase Attributes

The HTML standard does not require lowercase attribute names.

The title attribute (and all other attributes) can be written with uppercase or lowercase like title or TITLE.

However, W3C recommends lowercase attributes in HTML, and demands lowercase attributes for stricter document types like XHTML.

We Suggest: Always Quote Attribute Values

The HTML standard does not require quotes around attribute values.

However, W3C recommends quotes in HTML, and demands quotes for stricter document types like XHTML.

Good:

<a href=”https://www.w3schools.com/html/”>Visit our HTML tutorial</a>

Bad:

<a href=https://www.w3schools.com/html/>Visit our HTML tutorial</a>

Sometimes you have to use quotes. This example will not display the title attribute correctly, because it contains a space:

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

You will learn more about styles in our HTML Styles chapter.


The lang Attribute

You should always include the lang attribute inside the <html> tag, to declare the language of the Web page. This is meant to assist search engines and browsers.

The following example specifies English as the language:

<a href=”https://www.w3schools.com/html/”>Visit our HTML tutorial</a>

Example

<p title=About W3Schools>

Single or Double Quotes?

Double quotes around attribute values are the most common in HTML, but single quotes can also be used.

In some situations, when the attribute value itself contains double quotes, it is necessary to use single quotes:

<p title=’John “ShotGun” Nelson’>

Chapter Summary

  • . All HTML elements can have attributes
  • . The href attribute of <a> specifies the URL of the page the link goes to
  • . The src attribute of <img> specifies the path to the image to be displayed
  • . The width and height attributes of <img> provide size information for images
  • . The alt attribute of <img> provides an alternate text for an image
  • . The style attribute is used to add styles to an element, such as color, font, size, and more
  • . The lang attribute of the <html> tag declares the language of the Web page
  •  .The title attribute defines some extra information about an element

HTML Exercises

Exercise:

Add a “tooltip” to the paragraph below with the text “About W3Schools”.

<p =”About W3Schools”>W3Schools is a web developer’s site.</p>

CSS Padding

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

CSS Padding

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

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


Padding – Individual Sides

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

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

All the padding properties can have the following values:

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

Note: Negative values are not allowed.

Example

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

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

Padding – Shorthand Property

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

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

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

So, here is how it works:

If the padding property has four values:

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

Example

Use the padding shorthand property with four values:

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

If the padding property has three values:

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

Example

Use the padding shorthand property with three values:

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

If the padding property has two values:

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

Example

Use the padding shorthand property with two values:

div {
padding: 25px 50px;
}

If the padding property has one value:

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

Example

Use the padding shorthand property with one value:

div {
padding: 25px;
}

Padding and Element Width

The CSS width property specifies the width of the element’s content area. The content area is the portion inside the padding, border, and margin of an element (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.

Test Yourself With Exercises

Exercise:

Set the top padding of the <h1> element to 30 pixels.

<style>
h1 {
  : 30px;
}
</style>

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

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.

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

Example

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

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

Example

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

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

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!

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

Example

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

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

All CSS Dimension Properties

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: content, padding, borders and margins. 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 total width and height of an element, you must also include the padding and borders.

Example

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

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

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

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

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

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

Note: The margin property also affects the total space that the box will take up on the page, but the margin is not included in the actual size of the box. The box’s total width and height stops at the border.

Test Yourself With Exercises

Exercise:

Set the width of the <div> element to “200px”.

<style>
 {
  : ;
}
</style>

<body>

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

</body>

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

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

Example

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

Transparency using RGBA

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

Example

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

The CSS Background Color Property

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=”anonymous”></script>
</head>
<body>

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

</body>
</html>

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/bootstrap.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.

Styling Links

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

Example

{
color: hotpink;
}

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

The four links states are:

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

Example

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

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

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

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

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

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

Text Decoration

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

Example

I am messaga:link {
text-decoration: none;
}

a:visited {
text-decoration: none;
}

a:hover {
text-decoration: underline;
}

a:active {
text-decoration: underline;
}e box. Click edit button to change this text.

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

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

I am message box<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>. Click edit button to change this text.

CSS Lists

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

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

I am message box. Click edit button to change this text.

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:

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

Example

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

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

Remove Default Settings

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

Example

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

List – Shorthand property

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

Example

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

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

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

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


Styling List With Colors

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

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

Example

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

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

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

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

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

CSS Layout - The display Property

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


The display Property

The display property is used to specify how an element is shown on a web page.

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.

The display property is used to change the default display behavior of HTML elements.


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

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>
Value Description
inline Displays an element as an inline element
block Displays an element as a block element
contents Makes the container disappear, making the child elements children of the element the next level up in the DOM
flex Displays an element as a block-level flex container
grid Displays an element as a block-level grid container
inline-block Displays an element as an inline-level block container. The element itself is formatted as an inline element, but you can apply height and width values
inline-flex Displays an element as an inline-level flex container
inline-grid Displays an element as an inline-level grid container
inline-table The element is displayed as an inline-level table
list-item Let the element behave like a <li> element
run-in Displays an element as either block or inline, depending on context
table Let the element behave like a <table> element
table-caption Let the element behave like a <caption> element
table-column-group Let the element behave like a <colgroup> element
table-header-group Let the element behave like a <thead> element
table-footer-group Let the element behave like a <tfoot> element
table-row-group Let the element behave like a <tbody> element
table-cell Let the element behave like a <td> element
table-column Let the element behave like a <col> element
table-row Let the element behave like a <tr> element
none The element is completely removed
initial Sets this property to its default value
inherit Inherits this property from its parent element

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.

li {
display: inline;
}

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

Example

span {
display: block;
}

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

Example

{
display: block;
}

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

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;

Showing more display types
This example demonstrates some more display types.

Using CSS together with JavaScript to show content
This example demonstrates how to use CSS and JavaScript to show an element on click.

Exercise:

Hide the <h1> element. It should still take up the same space as before.

<style>
h1 {
  : ;
}
</style>

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

CSS Layout - width and max-width

Using width, max-width and margin: auto;

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

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

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

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:

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

Here is an example of the two divs above:

Example

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

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

CSS Layout - The position Property

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


The position Property

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

There are five different position values:

  • static
  • relative
  • fixed
  • absolute
  • sticky

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


position: static;

HTML elements are positioned static by default.

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

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

Here is the CSS that is used:

Example

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

position: relative;

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

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

Here is the CSS that is used:

Example

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

position: fixed;

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

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

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

Example

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

Here is the CSS that is used:

Example

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

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

position: sticky;

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

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

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

Example

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

Positioning Text In an Image

How to position text over an image:

CSS Layout - The z-index Property

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


The z-index Property

When elements are positioned, they can overlap other elements.

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

An element can have a positive or negative stack order:

This is a heading

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

Example

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

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

 

Another z-index Example

Example

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

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

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

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

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

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

</body>
</html>

Without z-index

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

Example

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

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

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

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

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

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

</body>
</html>

Test Yourself With Exercises

Exercise:

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

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

<style>
 {
  position: absolute;
  top: 0;
  : 1;  
}
 {
  position: absolute;
  top: 0;
  : 0;
}
</style>

<body>
  <h1 id="mytitle">This is a heading</h1>
  <p id="myintro">This is a paragraph</p>
</body>

CSS Layout - Overflow

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

CSS Overflow

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

The overflow property has the following values:

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

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

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


overflow: visible

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

Example

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

overflow: hidden

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

Example

div {
overflow: hidden;
}

overflow: scroll

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

Example

div {
overflow: scroll;
}

overflow: auto

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

Example

div {
overflow: auto;
}

overflow-x and overflow-y

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

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

Example

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

Test Yourself With Exercises

Exercise:

Force a scroll bar to the <div> element with class=”intro”.

<style>
.intro {
  width: 200px;
  height: 70px;
  : ;
}
</style>

<body>

<div class="intro">
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Phasellus imperdiet, nulla et dictum interdum,
nisi lorem egestas odio,
vitae scelerisque enim ligula venenatis dolor.
</div>

</body>

CSS Layout - display: inline-block

The display: inline-block Value

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

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

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

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

Example

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

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

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

Using inline-block to Create Navigation Links

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

Example

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

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

CSS Layout - Horizontal & Vertical Align

Center Align Elements

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

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

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

Example

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

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


Center Align Text

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

Example

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

Center an Image

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

Example

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

Left and Right Align – Using position

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

Example

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

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


Left and Right Align – Using float

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

Example

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

The clearfix Hack

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

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

Example

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

Center Vertically – Using padding

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

Example

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

Example

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

Center Vertically – Using line-height

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

Example

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

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

Center Vertically – Using position & transform

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

Example

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

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

Center Vertically – Using Flexbox

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

I am message box. Click edit button to change this text.

Example

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

CSS Combinators

CSS Combinators

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

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

There are four different combinators in CSS:

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

Descendant Selector

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

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

Example

div p {
background-color: yellow;
}

Child Selector (>)

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

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

Example

div > p {
background-color: yellow;
}

Adjacent Sibling Selector (+)

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

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

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

Example

div + p {
background-color: yellow;
}

General Sibling Selector (~)

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

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

Example

div ~ p {
background-color: yellow;
}

I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

CSS Pseudo-classes

What are Pseudo-classes?

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

For example, it can be used to:

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

Example

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

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

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

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

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


ADVERTISEMENT

Pseudo-classes and HTML Classes

Pseudo-classes can be combined with HTML classes:

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

Example

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


Hover on <div>

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

Example

div:hover {
background-color: blue;
}

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

I am message box. Click edit button to change this text.

p:first-child {
color: blue;
}

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

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

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>

CSS Pseudo-elements

What are Pseudo-Elements?

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

For example, it can be used to:

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

Syntax

The syntax of pseudo-elements:

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


The ::first-line Pseudo-element

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

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

Example

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

I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec

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

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

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

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

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

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

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


The ::first-letter Pseudo-element

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

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

Example

 

I am message box. Click edit button to change this text.

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

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

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

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

Pseudo-elements and HTML Classes

Pseudo-elements can be combined with HTML classes:

Example

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

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


Multiple Pseudo-elements

Several pseudo-elements can also be combined.

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

Example

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

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

CSS – The ::before Pseudo-element

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

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

Example

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

CSS – The ::after Pseudo-element

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

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

Example

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

CSS – The ::marker Pseudo-element

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

The following example styles the markers of list items:

Example

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

CSS – The ::selection Pseudo-element

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

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

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

Example

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

CSS Opacity / Transparency

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


Transparent Image

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

img {
opacity: 0.5;
}

Example

Example

img {
opacity: 0.5;
}

Transparent Hover Effect

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

HTML Images

HTML Images

HTML Image Maps


With HTML image maps, you can create clickable areas on an image.


Image Maps

The HTML <map> tag defines an image map. An image map is an image with clickable areas. The areas are defined with one or more <area> tags.

Try to click on the computer, phone, or the cup of coffee in the image below:

Example

Here is the HTML source code for the image map above:

<img src=”workplace.jpg” alt=”Workplace” usemap=”#workmap”>

<map name=”workmap”>
<area shape=”rect” coords=”34,44,270,350″ alt=”Computer” href=”computer.htm”>
<area shape=”rect” coords=”290,172,333,250″ alt=”Phone” href=”phone.htm”>
<area shape=”circle” coords=”337,300,44″ alt=”Coffee” href=”coffee.htm”>
</map>

How Does it Work?

The idea behind an image map is that you should be able to perform different actions depending on where in the image you click.

To create an image map you need an image, and some HTML code that describes the clickable areas.

The Image

The image is inserted using the <img> tag. The only difference from other images is that you must add a usemap attribute:

<img src=”workplace.jpg” alt=”Workplace” usemap=”#workmap”>

The usemap value starts with a hash tag # followed by the name of the image map, and is used to create a relationship between the image and the image map.

Create Image Map

Then, add a <map> element.

The <map> element is used to create an image map, and is linked to the image by using the required name attribute:

<map name=”workmap”>

The name attribute must have the same value as the <img>‘s usemap attribute .

The Areas

Then, add the clickable areas.

A clickable area is defined using an <area> element.

Shape

You must define the shape of the clickable area, and you can choose one of these values:

  • rect – defines a rectangular region
  • circle – defines a circular region
  • poly – defines a polygonal region
  • default – defines the entire region

You must also define some coordinates to be able to place the clickable area onto the image.


Shape=”rect”

The coordinates for shape="rect" come in pairs, one for the x-axis and one for the y-axis.

So, the coordinates 34,44 is located 34 pixels from the left margin and 44 pixels from the top:

Workplace

The coordinates 270,350 is located 270 pixels from the left margin and 350 pixels from the top:

Workplace

Now we have enough data to create a clickable rectangular area:

Example

<area shape=”rect” coords=”34, 44, 270, 350″ href=”computer.htm”>

This is the area that becomes clickable and will send the user to the page “coffee.htm”:

Workplace


Shape=”poly”

The shape="poly" contains several coordinate points, which creates a shape formed with straight lines (a polygon).

This can be used to create any shape.

Like maybe a croissant shape!

How can we make the croissant in the image below become a clickable link?

French Food

We have to find the x and y coordinates for all edges of the croissant:

French Food

The coordinates come in pairs, one for the x-axis and one for the y-axis:

Example

<area shape=”poly” coords=”140,121,181,116,204,160,204,222,191,270,140,329,85,355,58,352,37,322,40,259,103,161,128,147″ href=”croissant.htm”>

This is the area that becomes clickable and will send the user to the page “croissant.htm”:

French Food


Image Map and JavaScript

A clickable area can also trigger a JavaScript function.

Add a click event to the <area> element to execute a JavaScript function:

Example

Here, we use the onclick attribute to execute a JavaScript function when the area is clicked:

<map name=”workmap”>
<area shape=”circle” coords=”337,300,44″ href=”coffee.htm” onclick=”myFunction()”>
</map>

<script>
function myFunction() {
alert(“You clicked the coffee cup!”);
}
</script>

Chapter Summary

  • . Use the HTML <map> element to define an image map
  • . Use the HTML <area> element to define the clickable areas in the image map
  • . Use the HTML usemap attribute of the <img> element to point to an image map

HTML Image Tags

Tag

Description

<img> Defines an image
<map> Defines an image map
<area> Defines a clickable area inside an image map
<picture> Defines a container for multiple image resources

HTML Favicon

A favicon is a small image displayed next to the page title in the browser tab.

How To Add a Favicon in HTML

You can use any image you like as your favicon. You can also create your own favicon on sites like https://www.favicon.cc.

A favicon image is displayed to the left of the page title in the browser tab, like this:

Example of favicon

To add a favicon to your website, either save your favicon image to the root directory of your webserver, or create a folder in the root directory called images, and save your favicon image in this folder. A common name for a favicon image is “favicon.ico”.

Next, add a <link> element to your “index.html” file, after the <title> element, like this:

Example

<!DOCTYPE html>
<html>
<head>
<title>My Page Title</title>
<link rel=”icon” type=”image/x-icon” href=”/images/favicon.ico”>
</head>
<body>

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

</body>
</html>

Now, save the “index.html” file and reload it in your browser. Your browser tab should now display your favicon image to the left of the page title.

Favicon File Format Support

The following table shows the file format support for a favicon image:

Browser

ICO

PNG

GIF

JPEG

SVG

Edge Yes Yes Yes Yes Yes
Chrome Yes Yes Yes Yes Yes
Firefox Yes Yes Yes Yes Yes
Opera Yes Yes Yes Yes Yes
Safari Yes Yes Yes Yes Yes

Chapter Summary

  • . Use the HTML <link> element to insert a favicon

HTML Link Tag

I am message box. Click edit button to change this text.

Tag Description
<link> Defines the relationship between a document and an external resource

HTML Tables

HTML tables allow web developers to arrange data into rows and columns..

Example

Example

Company

Contact

Country

Alfreds Futterkiste Maria Anders Germany
Centro comercial Moctezuma Francisco Chang Mexico
Ernst Handel Roland Mendel Austria
Island Trading Helen Bennett UK
Laughing Bacchus Winecellars Yoshi Tannamuri Canada
Magazzini Alimentari Riuniti Giovanni Rovelli Italy

Define an HTML Table

A table in HTML consists of table cells inside rows and columns.

Example

A simple HTML table:

<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>

Table Cells

Each table cell is defined by a <td> and a </td> tag.

Everything between <td> and </td> are the content of the table cell.

Example

<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
</table>

Table Rows

Each table row starts with a <tr> and ends with a </tr> tag.

Example

<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>

Table Headers

Sometimes you want your cells to be table header cells. In those cases use the <th> tag instead of the <td> tag:

Example

Let the first row be table header cells:

<table>
<tr>
<th>Person 1</th>
<th>Person 2</th>
<th>Person 3</th>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>

By default, the text in <th> elements are bold and centered, but you can change that with CSS.


HTML Exercises

Exercise:

Add a table row with two table headers.

The two table headers should have the value “Name” and “Age”.

<table>




<tr>
<td>Jill Smith</td>
<td>50</td>
</tr>
</table>

HTML Table Tags

Tag Description
<table> Defines a table
<th> Defines a header cell in a table
<tr> Defines a row in a table
<td> Defines a cell in a table
<caption> Defines a table caption
<colgroup> Specifies a group of one or more columns in a table for formatting
<col> Specifies column properties for each column within a <colgroup> element
<thead> Groups the header content in a table
<tbody> Groups the body content in a table
<tfoot> Groups the footer content in a table

 

HTML Table Borders

HTML tables can have borders of different styles and shapes.

How To Add a Border

When you add a border to a table, you also add borders around each table cell:

To add a border, use the CSS border property on tableth, and td elements:

Example

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

HTML Table Padding & Spacing

HTML tables can adjust the padding inside the cells, and also the space between the cells.

With Padding
hello hello hello
hello hello hello
hello hello hello
With Spacing
hello hello hello
hello hello hello
hello hello hello

HTML Table – Cell Padding

Cell padding is the space between the cell edges and the cell content.

By default the padding is set to 0.

To add padding on table cells, use the CSS padding property:

Example

th, td {
padding: 15px;
}

To add padding only above the content, use the padding-top property.

And the others sides with the padding-bottompadding-left, and padding-right properties:

Example

th, td {
padding-top: 10px;
padding-bottom: 20px;
padding-left: 30px;
padding-right: 40px;
}

HTML Table – Cell Spacing

Cell spacing is the space between each cell.

By default the space is set to 2 pixels.

To change the space between table cells, use the CSS border-spacing property on the table element:

Example

table {
border-spacing: 30px;
}

HTML Table Colspan & Rowspan


HTML tables can have cells that span over multiple rows and/or columns.

NAME
APRIL
2022
FIESTA

HTML Table – Colspan

To make a cell span over multiple columns, use the colspan attribute:

Example

<table>
<tr>
<th colspan=”2″>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>43</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>57</td>
</tr>
</table>

HTML Table – Rowspan

To make a cell span over multiple rows, use the rowspan attribute:

Example

<table>
<tr>
<th>Name</th>
<td>Jill</td>
</tr>
<tr>
<th rowspan=”2″>Phone</th>
<td>555-1234</td>
</tr>
<tr>
<td>555-8745</td>
</tr>
</table>

HTML Exercises

Test Yourself With Exercises

Exercise:

Use the correct HTML attribute to make the first TH element span two columns.

<table>
<tr>
<th >Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>

HTML Table Styling

Use CSS to make your tables look better.


HTML Table – Zebra Stripes

If you add a background color on every other table row, you will get a nice zebra stripes effect.

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20

To style every other table row element, use the :nth-child(even) selector like this:

Example

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

HTML Table – Vertical Zebra Stripes

To make vertical zebra stripes, style every other column, instead of every other row.

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20

Set the :nth-child(even) for table data elements like this:

Example

td:nth-child(even), th:nth-child(even) {
background-color: #D6EEEE;
}

Combine Vertical and Horizontal Zebra Stripes

You can combine the styling from the two examples above and you will have stripes on every other row and every other column.

If you use a transparent color you will get an overlapping effect.

Use an rgba() color to specify the transparency of the color:

Example

tr:nth-child(even) {
background-color: rgba(150, 212, 212, 0.4);
}

th:nth-child(even),td:nth-child(even) {
background-color: rgba(150, 212, 212, 0.4);
}

Horizontal Dividers

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

If you specify borders only at the bottom of each table row, you will have a table with horizontal dividers.

Add the border-bottom property to all tr elements to get horizontal dividers:

Example

tr {
border-bottom: 1px solid #ddd;
}

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

Example

tr:hover {background-color: #D6EEEE;}

HTML Table Colgroup

If you want to style the two first columns of a table, use the <colgroup> and <col> elements.

MON TUE WED THU FRI SAT SUN
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28

The <colgroup> element should be used as a container for the column specifications.

Each group is specified with a <col> element.

The span attribute specifies how many columns that get the style.

The style attribute specifies the style to give the columns.

Example

<table>
<colgroup>
<col span=”2″ style=”background-color: #D6EEEE”>
</colgroup>
<tr>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>

Legal CSS Properties

There is only a very limited selection of CSS properties that are allowed to be used in the colgroup:

width property
visibility property
background properties
border properties

All other CSS properties will have no effect on your tables.

Multiple Col Elements

If you want to style more columns with different styles, use more <col> elements inside the <colgroup>:

Example

<table>
<colgroup>
<col span=”2″ style=”background-color: #D6EEEE”>
<col span=”3″ style=”background-color: pink”>
</colgroup>
<tr>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>

Empty Colgroups

If you want to style columns in the middle of a table, insert a “empty” <col> element (with no styles) for the columns before:

Example

<table>
<colgroup>
<col span=”3″>
<col span=”2″ style=”background-color: pink”>
</colgroup>
<tr>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>

Hide Columns

You can hide columns with the visibility: collapse property:

Example

<table>
<colgroup>
<col span=”2″>
<col span=”3″ style=”visibility: collapse”>
</colgroup>
<tr>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>

HTML Responsive Web Design

Responsive web design is about creating web pages that look good on all devices!

A responsive web design will automatically adjust for different screen sizes and viewports.


Responsive Web Design

What is Responsive Web Design?

Responsive Web Design is about using HTML and CSS to automatically resize, hide, shrink, or enlarge, a website, to make it look good on all devices (desktops, tablets, and phones):

Setting The Viewport

To create a responsive website, add the following <meta> tag to all your web pages:

Example

<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

This will set the viewport of your page, which will give the browser instructions on how to control the page’s dimensions and scaling.

Here is an example of a web page without the viewport meta tag, and the same web page with the viewport meta tag:

Without the viewport meta tag:
With the viewport meta tag:

Responsive Images

Responsive images are images that scale nicely to fit any browser size.

Using the width Property

If the CSS width property is set to 100%, the image will be responsive and scale up and down:

Example

<img src=”img_girl.jpg” style=”width:100%;”>

Notice that in the example above, the image can be scaled up to be larger than its original size. A better solution, in many cases, will be to use the max-width property instead.

Using the max-width Property

If the max-width property is set to 100%, the image will scale down if it has to, but never scale up to be larger than its original size:

Example

<img src=”img_girl.jpg” style=”max-width:100%;height:auto;”>

Show Different Images Depending on Browser Width

The HTML <picture> element allows you to define different images for different browser window sizes.

Resize the browser window to see how the image below changes depending on the width:

Example

<picture>
<source srcset=”img_smallflower.jpg” media=”(max-width: 600px)”>
<source srcset=”img_flowers.jpg” media=”(max-width: 1500px)”>
<source srcset=”flowers.jpg”>
<img src=”img_smallflower.jpg” alt=”Flowers”>
</picture>

Try it Yourself »

I am message box. Click edit button to change this text.

Responsive Text Size

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

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

Hello World

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

Example

<h1 style=”font-size:10vw>Hello World</h1>

I


Media Queries

In addition to resize text and images, it is also common to use media queries in responsive web pages.

With media queries you can define completely different styles for different browser sizes.

Example: resize the browser window to see that the three div elements below will display horizontally on large screens and stack vertically on small screens:

Main Content

Right Content

Example

<style>
.left, .right {
float: left;
width: 20%; /* The width is 20%, by default */
}

.main {
float: left;
width: 60%; /* The width is 60%, by default */
}

/* Use a media query to add a breakpoint at 800px: */
@media screen and (max-width: 800px) {
.left, .main, .right {
width: 100%; /* The width is 100%, when the viewport is 800px or smaller */
}
}
</style>

I am message box. Click edit button to change this text.

Responsive Web Page – Full Example

A responsive web page should look good on large desktop screens and on small mobile phones.

Responsive Web Design – Frameworks

All popular CSS Frameworks offer responsive design.

They are free, and easy to use.

W3.CSS

W3.CSS is a modern CSS framework with support for desktop, tablet, and mobile design by default.

W3.CSS is smaller and faster than similar CSS frameworks.

W3.CSS is designed to be independent of jQuery or any other JavaScript library.

W3.CSS Demo

Resize the page to see the responsiveness!

London

London is the capital city of England.

It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.

Paris

Paris is the capital of France.

The Paris area is one of the largest population centers in Europe, with more than 12 million inhabitants.

Tokyo

Tokyo is the capital of Japan.

It is the center of the Greater Tokyo Area, and the most populous metropolitan area in the world.

Example

<!DOCTYPE html>
<html>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<link rel=”stylesheet” href=”https://www.w3schools.com/w3css/4/w3.css”>
<body>

<div class=”w3-container w3-green”>
<h1>W3Schools Demo</h1>
<p>Resize this responsive page!</p>
</div>

<div class=”w3-row-padding”>
<div class=”w3-third”>
<h2>London</h2>
<p>London is the capital city of England.</p>
<p>It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.</p>
</div>

<div class=”w3-third”>
<h2>Paris</h2>
<p>Paris is the capital of France.</p>
<p>The Paris area is one of the largest population centers in Europe,
with more than 12 million inhabitants.</p>
</div>

<div class=”w3-third”>
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
<p>It is the center of the Greater Tokyo Area,
and the most populous metropolitan area in the world.</p>
</div>
</div>

</body>
</html>

I am message box. Click edit button to change this text.

Bootstrap

Another popular CSS framework is Bootstrap. Bootstrap uses HTML, CSS and jQuery to make responsive web pages.

Example

<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Bootstrap Example</title>
<meta charset=”utf-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css”>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js”></script>
<script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js”></script>
</head>
<body>

<div class=”container”>
<div class=”jumbotron”>
<h1>My First Bootstrap Page</h1>
</div>
<div class=”row”>
<div class=”col-sm-4″>

</div>
<div class=”col-sm-4″>

</div>
<div class=”col-sm-4″>

</div>
</div>
</div>

</body>
</html>

HTML Layout Elements and Techniques

Websites often display content in multiple columns (like a magazine or a newspaper).


Example

Cities

London

London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.

Standing on the River Thames, London has been a major settlement for two millennia, its history going back to its founding by the Romans, who named it Londinium.

Footer

HTML Layout Elements

HTML has several semantic elements that define the different parts of a web page:

HTML5 Semantic Elements
  • <header> – Defines a header for a document or a section
  • <nav> – Defines a set of navigation links
  • <section> – Defines a section in a document
  • <article> – Defines an independent, self-contained content
  • <aside> – Defines content aside from the content (like a sidebar)
  • <footer> – Defines a footer for a document or a section
  • <details> – Defines additional details that the user can open and close on demand
  • <summary> – Defines a heading for the <details> element

You can read more about semantic elements in our HTML Semantics chapter.

HTML Layout Techniques

There are four different techniques to create multicolumn layouts. Each technique has its pros and cons:

  • CSS framework
  • CSS float property
  • CSS flexbox
  • CSS grid

CSS Frameworks

If you want to create your layout fast, you can use a CSS framework, like W3.CSS or Bootstrap.

Cities

London

London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.

Standing on the River Thames, London has been a major settlement for two millennia, its history going back to its founding by the Romans, who named it Londinium.

Footer

CSS Flexbox Layout

Use of flexbox ensures that elements behave predictably when the page layout must accommodate different screen sizes and different display devices.

Learn more about flexbox in our CSS Flexbox chapter.

ExaMPLE

Cities

London

London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.

Standing on the River Thames, London has been a major settlement for two millennia, its history going back to its founding by the Romans, who named it Londinium.

Footer

HTML Layout Elements

HTML has several semantic elements that define the different parts of a web page:

HTML5 Semantic Elements
  • <header> – Defines a header for a document or a section
  • <nav> – Defines a set of navigation links
  • <section> – Defines a section in a document
  • <article> – Defines an independent, self-contained content
  • <aside> – Defines content aside from the content (like a sidebar)
  • <footer> – Defines a footer for a document or a section
  • <details> – Defines additional details that the user can open and close on demand
  • <summary> – Defines a heading for the <details> element

You can read more about semantic elements in our HTML Semantics chapter.

Cities

London

London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.

Standing on the River Thames, London has been a major settlement for two millennia, its history going back to its founding by the Romans, who named it Londinium.

Footer

I am message box. Click edit button to change this text.

Cities

London

London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.

Standing on the River Thames, London has been a major settlement for two millennia, its history going back to its founding by the Romans, who named it Londinium.

Footer

CSS Flexbox Layout

Use of flexbox ensures that elements behave predictably when the page layout must accommodate different screen sizes and different display devices.

Learn more about flexbox in our CSS Flexbox chapter.

Example

CSS Grid Layout

The CSS Grid Layout Module offers a grid-based layout system, with rows and columns, making it easier to design web pages without having to use floats and positioning.

Learn more about CSS grids in our CSS Grid Intro chapter.

HTML Entities


Reserved characters in HTML must be replaced with character entities.


HTML Entities

Some characters are reserved in HTML.

If you use the less than (<) or greater than (>) signs in your text, the browser might mix them with tags.

Character entities are used to display reserved characters in HTML.

A character entity looks like this:

&entity_name;

OR

&#entity_number;

To display a less than sign (<) we must write: &lt; or &#60;


Non-breaking Space

A commonly used entity in HTML is the non-breaking space: &nbsp;

A non-breaking space is a space that will not break into a new line.

Two words separated by a non-breaking space will stick together (not break into a new line). This is handy when breaking the words might be disruptive.

Examples:

  • . § 10
  •  . 10 km/h
  • .10 PM

Another common use of the non-breaking space is to prevent browsers from truncating spaces in HTML pages.

If you write 10 spaces in your text, the browser will remove 9 of them. To add real spaces to your text, you can use the &nbsp; character entity.

Some Useful HTML Character Entities

Result Description Entity Name Entity Number Try it
non-breaking space &nbsp; &#160; Try it »
< less than &lt; &#60; Try it »
> greater than &gt; &#62; Try it »
& ampersand &amp; &#38; Try it »
double quotation mark &quot; &#34; Try it »
single quotation mark (apostrophe) &apos; &#39; Try it »
¢ cent &cent; &#162; Try it »
£ pound &pound; &#163; Try it »
¥ yen &yen; &#165; Try it »
euro &euro; &#8364; Try it »
© copyright &copy; &#169; Try it »
® registered trademark &reg; &#174;

Using Emojis in HTML

Emojis are characters from the UTF-8 character set: 😄 😍 💗


What are Emojis?

Emojis look like images, or icons, but they are not.

They are letters (characters) from the UTF-8 (Unicode) character set.

Emojis are characters from the UTF-8 character set: 😄 😍 💗


What are Emojis?

Emojis look like images, or icons, but they are not.

They are letters (characters) from the UTF-8 (Unicode) character set.

The HTML charset Attribute

To display an HTML page correctly, a web browser must know the character set used in the page.

This is specified in the <meta> tag:

<meta charset=”UTF-8″>

UTF-8 Characters

Many UTF-8 characters cannot be typed on a keyboard, but they can always be displayed using numbers (called entity numbers):

  • A is 65
  • B is 66
  • C is 67

Example

<!DOCTYPE html>
<html>
<head>
<meta charset=”UTF-8″>
</head>
<body>

<p>I will display A B C</p>
<p>I will display &#65; &#66; &#67;</p>

</body>
</html>

Example Explained

The <meta charset="UTF-8"> element defines the character set.

The characters A, B, and C, are displayed by the numbers 65, 66, and 67.

To let the browser understand that you are displaying a character, you must start the entity number with &# and end it with ; (semicolon).


Emoji Characters

Emojis are also characters from the UTF-8 alphabet:

  • 😄 is 128516
  • 😍 is 128525
  • 💗 is 128151

<!DOCTYPE html>
<html>
<head>
<meta charset=”UTF-8″>
</head>
<body>

<h1>My First Emoji</h1>

<p>&#128512;</p>

</body>
</html>

Since Emojis are characters, they can be copied, displayed, and sized just like any other character in HTML.

Example

 

<!DOCTYPE html>
<html>
<head>
<meta charset=”UTF-8″>
</head>
<body>

<h1>Sized Emojis</h1>

<p style=”font-size:48px”>
&#128512; &#128516; &#128525; &#128151;
</p>

</body>
</html>

Some Emoji Symbols in UTF-8

Emoji Value Try it
🗻 &#128507; Try it »
🗼 &#128508; Try it »
🗽 &#128509; Try it »
🗾 &#128510; Try it »
🗿 &#128511; Try it »
😀 &#128512; Try it »
😁 &#128513; Try it »
😂 &#128514; Try it »
😃 &#128515; Try it »
😄 &#128516; Try it »
😅 &#128517;