- CSS Introduction
- CSS Syntax
- CSS Selectors
- How To Add CSS
- CSS Comments
- CSS Padding
- CSS Height/Width
- CSS Box Model
- CSS background-color
- CSS Icons
- CSS Links
- CSS Lists
- CSS display
- CSS max-width
- CSS position
- CSS Z-index
- CSS Overflow
- CSS Layout -Inline-block
- CSS - Align
- CSS Combinators
- CSS Pseudo-classes
- CSS Pseudo-elements
- CSS Opacity
- HTML Images
- HTML Images
- HTML Image Maps
- HTML Favicon
- HTML Tables
- HTML Table Borders
- HTML Table Padding & Spacing
- HTML Table Colspan & amp; Rowspan
- HTML Table Styling
- HTML Table Colgroup
- HTML Responsive Web Design
- HTML Layout Elements
- HTML Entities
- Using Emojis in HTML
CSS Introduction
CSS is the language we use to style a Web page.
What is CSS?
- CSS stands for Cascading Style Sheets
- CSS describes how HTML elements are to be displayed on screen, paper, or in other media
- CSS saves a lot of work. It can control the layout of multiple web pages all at once
- External stylesheets are stored in CSS files
-
CSS Demo – One HTML Page – Multiple Styles!
Here we will show one HTML page displayed with four different stylesheets. Click on the “Stylesheet 1”, “Stylesheet 2”, “Stylesheet 3”, “Stylesheet 4” links below to see the different styles:
Why Use CSS?
CSS is used to define styles for your web pages, including the design, layout and variations in display for different devices and screen sizes.
CSS Example
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
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, andred
is the property valuetext-align
is a property, andcenter
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:
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″:
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:
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:
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:
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):
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:
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:
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”
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:
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:
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:
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:
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”:
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:
- Inline style (inside an HTML element)
- External and internal style sheets (in the head section)
- 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
You can add comments wherever you want in the code:
Example
Even in the middle of a code line:
Example
Comments can also span multiple lines:
Example
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
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:
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
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:
Bad:
Sometimes you have to use quotes. This example will not display the title attribute correctly, because it contains a space:
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:
Example
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:
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
andheight
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”.
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:
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:
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:
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:
If the padding
property has one value:
- padding: 25px;
- all four paddings are 25px
Example
Use the padding shorthand property with one value:
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):
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:
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.
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 widthlength
– Defines the height/width in px, cm, etc.%
– Defines the height/width in percent of the containing blockinitial
– Sets the height/width to its default valueinherit
– 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:
Example
Set the height and width of another <div> 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!
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:
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:
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:
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.
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:
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:
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
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
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
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
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
CSS Links
With CSS, links can be styled in many different ways.
Styling Links
Links can be styled with any CSS property (e.g. color
, font-family
, background
, etc.).
Example
In addition, links can be styled differently depending on what state they are in.
The four links states are:
a:link
– a normal, unvisited linka:visited
– a link the user has visiteda:hover
– a link when the user mouses over ita:active
– a link the moment it is clicked
Example
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
Link Buttons
This example demonstrates a more advanced example where we combine several CSS properties to display links as boxes/buttons:
Example
This example demonstrates the different types of cursors (can be useful for links):
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
An Image as The List Item Marker
The list-style-image
property specifies an image as the list item marker:
Example
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:
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
List – Shorthand property
The list-style
property is a shorthand property. It is used to set all the list properties in one declaration:
Example
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
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>
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.
The following example displays <span> elements as block elements:
Example
The following example displays <a> elements as block elements:
Example
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
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
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.
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:
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
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
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
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
Here is the CSS that is used:
Example
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
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
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:
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:
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 boxhidden
– The overflow is clipped, and the rest of the content will be invisiblescroll
– The overflow is clipped, and a scrollbar is added to see the rest of the contentauto
– Similar toscroll
, 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
overflow: hidden
With the hidden
value, the overflow is clipped, and the rest of the content is hidden:
Example
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
overflow: auto
The auto
value is similar to scroll
, but it adds scrollbars only when necessary:
Example
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
CSS Layout - display: inline-block
The display: inline-block Value
Compared to display: inline
, the major difference is that display: inline-block
allows to set a width and height on the element.
Also, with display: inline-block
, the top and bottom margins/paddings are respected, but with display: inline
they are not.
Compared to display: block
, the major difference is that display: inline-block
does not add a line-break after the element, so the element can sit next to other elements.
The following example shows the different behavior of display: inline
, display: inline-block
and display: block
:
Example
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
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
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 an Image
To center an image, set left and right margin to auto
and make it into a block
element:
Example
Left and Right Align – Using position
One method for aligning elements is to use position: absolute;
:
Example
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
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
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
Example
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 Vertically – Using position & transform
If padding
and line-height
are not options, another solution is to use positioning and the transform
property:
Example
Center Vertically – Using Flexbox
You can also use flexbox to center things. Just note that flexbox is not supported in IE10 and earlier versions:
Example
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
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
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
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
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
Note: a:hover
MUST come after a:link
and a:visited
in the CSS definition in order to be effective! a:active
MUST come after a:hover
in the CSS definition in order to be effective! Pseudo-class names are not case-sensitive.
Pseudo-classes and HTML Classes
Pseudo-classes can be combined with HTML classes:
When you hover over the link in the example, it will change color:
Example
Hover on <div>
An example of using the :hover
pseudo-class on a <div> element:
Example
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
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
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
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
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:
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
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
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
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
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
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
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
CSS – The ::selection Pseudo-element
The ::selection
pseudo-element matches the portion of an element that is selected by a user.
The following CSS properties can be applied to ::selection
: color
, background
, cursor
, and outline
.
The following example makes the selected text red on a yellow background:
Example
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:
Example
Example
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:
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:
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:
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 regioncircle
– defines a circular regionpoly
– defines a polygonal regiondefault
– 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:
The coordinates 270,350
is located 270 pixels from the left margin and 350 pixels from the top:
Now we have enough data to create a clickable rectangular area:
Example
This is the area that becomes clickable and will send the user to the page “coffee.htm”:
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?
We have to find the x and y coordinates for all edges of the croissant:
The coordinates come in pairs, one for the x-axis and one for the y-axis:
Example
This is the area that becomes clickable and will send the user to the page “croissant.htm”:
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:
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
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:
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
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:
Chapter Summary
- . Use the HTML
<link>
element to insert a favicon
HTML Link Tag
HTML Tables
HTML tables allow web developers to arrange data into rows and columns..
Example
Example
Define an HTML Table
A table in HTML consists of table cells inside rows and columns.
Example
A simple HTML 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 Rows
Each table row starts with a <tr>
and ends with a </tr>
tag.
Example
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:
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”.
HTML Table Tags
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 table
, th
, and td
elements:
Example
HTML Table Padding & Spacing
HTML tables can adjust the padding inside the cells, and also the space between the cells.
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
To add padding only above the content, use the padding-top
property.
And the others sides with the padding-bottom
, padding-left
, and padding-right
properties:
Example
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
HTML Table Colspan & Rowspan
HTML tables can have cells that span over multiple rows and/or columns.
HTML Table – Colspan
To make a cell span over multiple columns, use the colspan
attribute:
Example
HTML Table – Rowspan
To make a cell span over multiple rows, use the rowspan
attribute:
Example
HTML Exercises
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.
To style every other table row element, use the :nth-child(even)
selector like this:
Example
HTML Table – Vertical Zebra Stripes
To make vertical zebra stripes, style every other column, instead of every other row.
Set the :nth-child(even)
for table data elements like this:
Example
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
Horizontal Dividers
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
Hoverable Table
Use the :hover
selector on tr
to highlight table rows on mouse over:
Example
HTML Table Colgroup
If you want to style the two first columns of a table, use the <colgroup>
and <col>
elements.
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
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
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
Hide Columns
You can hide columns with the visibility: collapse
property:
Example
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.
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
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:
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
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
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
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
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
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
Bootstrap
Another popular CSS framework is Bootstrap. Bootstrap uses HTML, CSS and jQuery to make responsive web pages.
Example
HTML Layout Elements and Techniques
Websites often display content in multiple columns (like a magazine or a newspaper).
Example
HTML Layout Elements
HTML has several semantic elements that define the different parts of a web page:
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 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
HTML Layout Elements
HTML has several semantic elements that define the different parts of a web page:
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:
To display a less than sign (<) we must write: < or <
Non-breaking Space
A commonly used entity in HTML is the non-breaking space:
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 character entity.
Some Useful HTML Character Entities
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:
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
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
Since Emojis are characters, they can be copied, displayed, and sized just like any other character in HTML.
Example