CSS Basics Summary

2020-Apr-28

🚴 w3schools CSS Basics

🏫 w3schools How To

💨 by Eugene Ruthven

email Feedback About This Page

This is my summary of w3schools' CSS - The Basics in a one page/file format - using only HTML5/CSS3. It can be used as a quick reference. Quick? There are many details in CSS. Concentrate on a few CSS styles to create your own small library.

📚 w3schools CSS Reference

1. Syntax 21. Layout - The position Property
2. Selectors 22. Layout - Overflow
3. How To Add CSS 23. Layout - float and clear
4. Comments 24. Layout - display: inline-block
5. Colors 25. Layout - Horizontal & Vertical Align
6. Backgrounds 26. Combinators
7. Borders 27. Pseudo-classes
8. Margins 28. Pseudo-elements
9. Padding 29. Opacity / Transparency
10. Height and Width 30. Navigation Bar
11. Box Model 31. Dropdowns
12. Outline 32. Image Gallery
13. Text 33. Image Sprites
14. Fonts 34. Attribute Selectors
15. Icons 35. Forms
16. Links 36. Counters
17. Lists 37. Website Layout
18. Tables 38. Units
19. Layout: Display 39. Specificity
20. Layout: max-width  

CSS is a language that describes the style of an HTML document.

CSS describes how HTML elements should be displayed.

CSS stands for Cascading Style Sheets:

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

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:

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!

The style definitions are normally saved in external .css files.

With an external stylesheet file, you can change the look of an entire website by changing just one file!


CSS Syntax

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

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

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

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

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


CSS Selectors

We can divide CSS selectors into five categories:
1. Simple select elements based on name, id, class, all or group
2. Combinator select elements based on a specific relationship between them
3. Pseudo-class select elements based on a certain state
4. Pseudo-elements select and style a part of an element
5. Attribute select elements based on an attribute or attribute value

1. CSS element Selector

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

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

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

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

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

HTML elements can also refer to more than one class. <p class="center large">This paragraph refers to two classes.</p>

📝 Note: A class name cannot start with a number!

4. The CSS Universal Selector

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

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

from this:

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

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

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

In group selectors, separate each selector with a comma.


How To Add CSS

There are three ways of using styles:
External CSS look of an entire website set by one file
use <link> element, in <head></head> section
has.css extension
Internal CSS defined inside the <style></style> element, inside the <head></head> section
Inline CSS style attribute to desired element - can contain any CSS property

📝 Note:Do not add a space between the property value and the unit ie. margin-left:20px;. No mention is made about spacing between selector and left curly bracket.

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

Multiple Style Sheets

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

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


CSS Comments

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

Comments are ignored by browsers.

A CSS comment starts with /* and ends with */

Comments can added anywhere in the code.

Comments can span multiple lines.


CSS Colors

📚 🎓 Advanced There are 140 standard color names.

Background background-color property
Text color property
Border border property ie. border:2px solid DodgerBlue;

Colors can be specified using:
color names    
RGB rgb(red, green, blue) Each parameter defines the intensity of the color between 0 and 255
RGBA rgba(red, green, blue, alpha) extension of RGB color values with an alpha channel - which specifies the opacity for a color. alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at all)
HEX #rrggbb rr (red), gg (green) and bb (blue) are hexadecimal values between 00 and ff (decimal 0-255)
HSL hsl(hue, saturation, lightness) Hue = a degree on the color wheel from 0 to 360. 0 is red, 120 is green, and 240 is blue
Saturation = a percentage value, 0% means a shade of gray, and 100% is the full color
Lightness = a percentage, 0% is black, 50% is neither light or dark, 100% is white
HSLA hsla(hue, saturation, lightness, alpha) extension of HSL color values with an alpha channel - which specifies the opacity for a color alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at all)

CSS Backgrounds

background properties used to define the background effects for elements:
  1. background-color specifies the background color of an element

  2. background-image specifies an image to use as the background of an element -by default, the image is repeated so it covers the entire element.

  3. background-repeat By default, the background-image property repeats an image both horizontally and vertically
    background-repeat:no-repeat Shows background image only once
    background-position property is used to specify the position of the background image.

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

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

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

  5. background is shorthand to specify all the background properties in one single property:
    from:

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

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

  1. background-color
  2. background-image
  3. background-repeat
  4. background-attachment
  5. background-position

All CSS Background Properties:
PropertyDescription
background Sets all the background properties in one declaration
background-attachment Sets whether a background image is fixed or scrolls with the rest of the page
background-clip Specifies the painting area of the background
background-color Sets the background color of an element
background-image Sets the background image for an element
background-origin Specifies where the background image(s) is/are positioned
background-position Sets the starting position of a background image
background-repeat Sets how a background image will be repeated
background-size Specifies the size of the background image(s)

Opacity/Transparency

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

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

Transparency using RGBA

If you do not want to apply opacity to child elements, use RGBA color values. ie. set opacity for background color- not the text.


CSS Borders

border properties specify an element's border:

1. CSS Border Style

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

The following values are allowed:
dotted Defines a dotted border
dashed Defines a dashed border
solid Defines a solid border
double Defines a double border
groove Defines a 3D grooved border. The effect depends on the border-color value
ridge Defines a 3D ridged border. The effect depends on the border-color value
inset Defines a 3D inset border. The effect depends on the border-color value
outset Defines a 3D outset border. The effect depends on the border-color value
none Defines no border
hidden Defines a hidden border

 

p.dotted {
  border-style:dotted;
}

border-style property can have from one to four values - for:

📝 Note:None of the OTHER CSS border properties will have ANY effect unless the border-style property is set!

2. CSS Border Width

border-width property specifies the width of the four borders

The width can be set as a specific size:

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

Specific Side Widths

The border-width property can have from one to four values:

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

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

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

3. CSS Border Color

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

The color can be set by:
name specify a color name, like red
HEX specify a HEX value, like #ff0000
RGB specify a RGB value, like rgb(255,0,0)
HSL specify a HSL value, like hsl(0, 100%, 50%)
transparent  

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

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

Specific Side Colors

The border-color property can have from one to four values:

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

 

border color can be specified using:
names border-color:red green blue yellow; /*top right bottom left */
hex border-color:#ff0000; /* red */
rgb border-color:rgb(255, 0, 0); /* red */
hsl border-color:hsl(0, 100%, 50%); /* red */

4. CSS Border Sides

Individual Sides
it is possible to specify a different border for each side.

There are properties for specifying each of the borders:

this:
p {
  border-top-style:dotted;
  border-right-style:solid;
  border-bottom-style:dotted;
  border-left-style:solid;
}
or this:
p {
  border-style: dotted solid;
}
are the same.

If the border-style property has four values:

If the border-style property has three values:

If the border-style property has two values:

If the border-style property has one value:

The border-style property also works with border-width and border-color.

5. CSS Using the Shorthand Border Property

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

border property is shorthand for the following individual border properties:

p {
  border:5px solid red;
}

can specify all the individual border properties for just one side:
p {
  border-left:6px solid red;
  background-color:lightgrey;
}

6. CSS Rounded Borders

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

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

All CSS Border Properties
PropertyDescription
border Sets all the border properties in one declaration
border-bottom Sets all the bottom border properties in one declaration
border-bottom-color Sets the color of the bottom border
border-bottom-style Sets the style of the bottom border
border-bottom-width Sets the width of the bottom border
border-color Sets the color of the four borders
border-left Sets all the left border properties in one declaration
border-left-color Sets the color of the left border
border-left-style Sets the style of the left border
border-left-width Sets the width of the left border
border-radius Sets all the four border-*-radius properties for rounded corners
border-right Sets all the right border properties in one declaration
border-right-color Sets the color of the right border
border-right-style Sets the style of the right border
border-right-width Sets the width of the right border
border-style Sets the style of the four borders
border-top Sets all the top border properties in one declaration
border-top-color Sets the color of the top border
border-top-style Sets the style of the top border
border-top-width Sets the width of the top border
border-width Sets the width of the four borders

CSS Margins

Margin properties are used to create space around elements, outside of any defined borders.

Can have full control over the margins.

There are properties for setting the margin for each side of an element:

1. Margin - Individual Sides

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

All the margin properties can have the following values:
auto the browser calculates the margin
length specifies a margin in px, pt, cm, etc. - to get 0 top try: margin-top:-1.0em;
% specifies a margin in % of the width of the containing element
inherit specifies that the margin should be inherited from the parent element

📎 Tip: Negative values are allowed.

p {
  /*margin-top:-1.0em; to get 0 top try:  margin-top:-1.0em;*/
  margin-top:100px;
  margin-bottom:100px;
  margin-right:150px;
  margin-left:80px;
}

2. Shorthand: margin property

margin property is shorthand for all the margin properties.

margin property is shorthand for the following individual margin properties:

If the margin property has four values:

If the margin property has three values:

If the margin property has two values:

If the margin property has one value:

3. The auto Value

Setting margin property to auto will horizontally center the element within its container.

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

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

4. The inherit Value

This example lets the left margin of the <p class="ex1"> element be inherited from the parent element (<div>):
div {
  border:1px solid red;
  margin-left:100px;
}

p.ex1 {
  margin-left:inherit;
}

5. CSS Margin Collapse

Top and bottom margins of elements are sometimes collapsed into a single margin that is equal to the largest of the two margins.

This does not happen on left and right margins! Only top and bottom margins!

All CSS Margin Properties
PropertyDescription
margin shorthand to set margin properties in one declaration
margin-bottom sets bottom margin of an element
margin-left sets left margin of an element
margin-right sets right margin of an element
margin-top sets top margin of an element

CSS Padding

Used to generate space around an element's content, inside of any defined borders.

You have full control over padding.

There are properties for setting the padding for each side of an element:

1. Padding - Individual Sides

Properties for specifying the padding for each side of an element:

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.

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

2. Shorthand: padding property

padding property is shorthand for the following individual padding properties:

If the padding property has four values:

If the padding property has three values:

If the padding property has two values:

If the padding property has one value:

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

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.

Can use the box-sizing property. This causes the element to maintain its width; if you increase the padding, the available content space will decrease.

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

All CSS Padding Properties
PropertyDescription
padding shorthand property for setting all padding properties in one declaration
padding-bottom sets bottom padding of an element
padding-left sets left padding of an element
padding-right sets right padding of an element
padding-top sets top padding of an element

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

1. height and width Values

may have the following values:
auto default - browser calculates the height and width
length defines height/width in px, cm etc.
% defines height/width in percent of containing block
initial sets height/width to its default value
inherit the height/width will be inherited from its parent value

2. Setting max-width

The max-width property is used to set the maximum width of an element.

The max-width can be specified in:

A commom problem with a <div> occurs when the browser window is smaller than the width of the element (ie. 500px). The browser will add a horizontal scrollbar to the page.

Using max-width instead, in this situation, will improve the browser's handling of small windows.

All CSS Dimension Properties
PropertyDescription
height sets height of an element
max-height sets maximum height of an element
max-width sets maximum width of an element
min-height sets minimum height of an element
min-width sets minimum width of an element
width sets width of an element

CSS Box Model

All HTML elements can be considered as boxes. In CSS, the term box model is used when talking about design and layout.

The CSS box model is essentially a box that wraps around every HTML element.
It consists of:

The image below illustrates the box model:

Margin
Border
Padding
Content
or see it at:

🚴 w3schools box model

Explanation of the different parts:
Content content of the box, where text and images appear
Padding Clears an area around the content - 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 adding a border around elements, and to define space between elements.

Width and Height of an Element

Need to know how the box model works to set width and height of an element correctly in all browsers,

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

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

Here is the calculation:

total width of an element calculated:
Total element width = width + left padding + right padding + left border + right border + left margin + right margin

total height of an element calculated:
Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin


CSS Outline

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

w3schools outline

or see it at:

🚴 w3schools outline

CSS has the following outline properties:

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

1. CSS Outline Style

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

p.dotted{
  outline-style:dotted;
}

2. CSS Outline Width

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

2. CSS Outline Color

The outline-color property is used to set the color of the outline.

The color can be set by:
name specify a color name, like red
HEX specify a hex value, like #ff0000
RGB specify a RGB value, like rgb(255,0,0)
HSL specify a HSL value, like hsl(0, 100%, 50%)
invert performs a color inversion - which ensures that the outline is visible, regardless of color background

outline-color:red;
outline-color:#ff0000; /* red */
outline-color:rgb(255, 0, 0); /* red */
outline-color:hsl(0, 100%, 50%); /* red */
outline-color:invert;

3. CSS Outline Property Shorthand

outline property is shorthand for setting the following individual outline properties:


CSS Text

1. Text Color

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

📚 w3schools CSS Legal Color Values

The default text color for a page is defined in the body selector.
body {
  color:blue;
}

2. Text Color and Background Color

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

3. Text Alignment

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

A text can be:

h1 {
  text-align:center;
}

h2 {
  text-align:left;
}

h3 {
  text-align:right;
}

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

4. Text Direction

The direction and unicode-bidi properties can be used to change the text direction of an element:
p {
  direction:rtl;
  unicode-bidi:bidi-override;
}

5. Vertical Alignment

The vertical-align property sets the vertical alignment of an element:
img.top {
  vertical-align:top;
}

img.middle {
  vertical-align:middle;
}

img.bottom {
  vertical-align:bottom;
}

6. Text Decoration

The text-decoration property is used to set or remove decorations from text.

text-decoration:none; often used to remove underlines from links

a {
  text-decoration:none;
}

other text-decoration values:

7. Text Transformation

text-transform property specifies uppercase and lowercase letters in text

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

8. Text Spacing/Text Indentation

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

9. Letter Spacing

letter-spacing property used to specify the space between the characters in text:
h1 {
  letter-spacing:3px;
}

h2 {
  letter-spacing:-3px;
}

10. Line Height

The line-height property is used to specify the space between lines:
p.small {
  line-height:0.8;
}

p.big {
  line-height:1.8;
}

11. Word Spacing

word-spacing property specifies space between words in a chunk of text
h1 {
  word-spacing:10px;
}

h2 {
  word-spacing:-5px;
}

12. White Space

white-space property specifies how white-space inside an element is handled
p {
  white-space:nowrap; /*disable text wrapping inside an element*/
}

13. Text Shadow

text-shadow property adds shadow text

In its simplest use, only specify the horizontal shadow (2px) and the vertical shadow (2px):
h1 {
  text-shadow:2px 2px;
}

h1 {
  text-shadow:2px 2px red; /*add color red*/
}

h1 {
  text-shadow:2px 2px 5px red; /*add blur effect 5px*/
}

All CSS Text Properties
PropertyDescription
color sets color of text
direction specifies text direction/writing direction
letter-spacing increases or decreases space between characters in a text
line-height sets line height
text-align specifies horizontal alignment of text
text-decoration specifies decoration added to text
text-indent specifies indentation of the first line in a text-block
text-shadow specifies shadow effect added to text
text-transform controls capitalization of text
text-overflow specifies how overflowed content that is not displayed should be signaled to the user
unicode-bidi used together with direction property to set or return whether the text should be overridden to support multiple languages in the same document
vertical-align sets vertical alignment of an element
white-space specifies how white-space inside an element is handled
word-spacing increases or decreases space between words in a text

CSS Fonts

The CSS font properties define the following for text:

1. CSS Font Families

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

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

2. Font Family

The font family of text is set with the font-family property.

The font-family property should hold several font names as a fallback system. If the browser does not support the first font, it tries the next font, and so on.

Start with the font you want, and end with a generic family, to let the browser pick a similar font in the generic family, if no other fonts are available.

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

More than one font family is specified in a comma-separated list:
.serif {
  font-family:"Times New Roman", Times, serif;
}

🚴 w3schools Web Safe Font Combinations

3. Font Style

font-style property has three values:

p.normal {
  font-style:normal;
}

p.italic {
  font-style:italic;
}

p.oblique {
  font-style:oblique;
}

4. Font Weight

font-weight property specifies the weight of a font:
p.normal {
  font-weight:normal;
}

p.thick {
  font-weight:bold;
}

5. Font Variant

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

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

p.normal {
  font-variant:normal;
}

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

6. Font Size

font-size property sets text size

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

Always use the proper HTML tags, like <h1> - <h6> for headings and <p> for paragraphs.

The font-size value can be:

Absolute size:

Relative size:

📝 Note: If font size is not specified, the default size for normal text, like paragraphs, is 16px (16px=1em).

7. Set Font Size With Pixels

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

h1 {
  font-size:40px;
}

8. Set Font Size With Em

Many developers use em instead of pixels to allow users to resize the text in the browser menu.

The em size unit is recommended by the W3C.

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

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

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

9. Use a Combination of Percent and Em

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

body {
  font-size:100%;
}

h1 {
  font-size:2.5em;
}

10. Responsive Font Size

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:

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

11. Shorthand: Font Property

The font property is shorthand for:

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

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

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

All CSS Font Properties
PropertyDescription
font sets all font properties in one declaration
font-family specifies font family for text
font-size specifies font size of text
font-style specifies font style for text
font-variant specifies whether or not text should be displayed in a small-caps font
font-weight specifies weight of a font

CSS Icons

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

2. Font Awesome Icons

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

Read more about how to get started with Font Awesome at 📚 🎓 w3schools Font Awesome 5 tutorial.

📝 Note: No downloading or installation is required!

example:
<!DOCTYPE html>
<html>
<head>
<script src="https://kit.fontawesome.com/a076d05399.js"></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>

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

3. Bootstrap Icons

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

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

4. Google Icons

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

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

For a complete list of all icons, visit 📚 w3schools Icons Tutorial.
(Only adds a little more info than what's above.)


CSS Links

Links can be styled in different ways.

1. Styling Links

Links can be styled with any CSS property.

Links can be styled differently depending on what state they are in.

The four links states are:

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

2. Text Decoration

The text-decoration property is mostly used to remove underlines from links:
a:link {
  text-decoration:none;
}

3. Background Color

The background-color property can be used to specify a background color for links:
a:link {
  background-color:yellow;
}

4. Link Buttons

Advanced example combining several CSS properties to display links as boxes/buttons:
a:link, a:visited {
  background-color:#f44336;
  color:white;
  padding:14px 25px;
  text-align:center;
  text-decoration:none;
  display:inline-block;
}

CSS Lists

1. HTML Lists and CSS List Properties

In HTML, there are two main types of lists:

The CSS list properties allow you to:

2. Different List Item Markers

The list-style-type property specifies the type of list item marker:
ul.a {
  list-style-type:circle; /*unordered list*/
}

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

3. An Image as The List Item Marker

The list-style-image property specifies an image as the list item marker:
ul {
  list-style-image:url('sqpurple.gif');
}

4. 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 bullet points will be outside the list item. The start of each line of a list item will be aligned vertically. This is the default.

list-style-position:inside; means 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.

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

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

5. Remove Default Settings

The list-style-type:none property can also be used to remove 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>:
ul {
  list-style-type:none;
  margin:0;
  padding:0;
}

6. Shorthand: List property

list-style property is shorthand. It is used to set all the list properties in one declaration:
ul {
  list-style:square inside url("sqpurple.gif");
}

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

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

  2. list-style-position specifies whether list-item markers should appear inside or outside the content flow

  3. list-style-image specifies an image as list item marker

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

7. Styling List With Colors

Can also style lists with colors, to make them look a more interesting.

Anything added to the <ol> or <ul> tag, affects the entire list, while properties added to <li> tag will affect individual list item:
ol {
  background:#ff9999;
  padding:20px;
}

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

All CSS List Properties
PropertyDescription
list-style sets all properties for a list in one declaration
list-style-image specifies an image as list-item marker
list-style-position specifies position of the list-item markers bullet points
list-style-type specifies type of list-item marker

CSS Tables

more details/examples at:

1. Table Borders

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

Notice: When the above code is used the table will have double borders. This is because the table and the <th> and <td> elements have separate borders.

2. Collapse Table Borders

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

table, th, td {
  border:1px solid black;
}
To only have a border around the table, only specify the border property for <table>:
table {
  border:1px solid black;
}

3. Table Width and Height

Width and height of a table are defined by the width and height properties:
table {
  width:100%;
}

th {
  height:50px;
}

4. Horizontal Alignment

The text-align property sets the horizontal alignment:

of the content in <th> or <td>.

By default, the content of <th> elements are center-aligned and the content of <td> elements are left-aligned.

th {
  text-align:left;
}

5. Vertical Alignment

The vertical-align property sets the vertical alignment:

of the content in <th> or <td>.

By default, the vertical alignment of the content in a table is middle - for both <th> and <td> elements.

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

6. Table Padding

Use padding property to control the space between the border and the content in a table on <td> and <th> elements:
th, td {
  padding:15px;
  text-align:left;
}

7. Horizontal Dividers

Add border-bottom property to <th> and <td> for horizontal dividers:
th, td {
  border-bottom:1px solid #ddd;
}

8. Hoverable Table

Use the :hover selector on <tr> to highlight table rows on mouseover:
tr:hover {
  background-color:#f5f5f5;
}

9. Striped Tables

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

10. Table Color

th {
  background-color:#4CAF50;  
  color:white;
}

11. Responsive Table

A responsive table will display a horizontal scroll bar if the screen is too small to display the full content.

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

<table>
... table content ...
</table>

</div>

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

CSS Table Properties
PropertyDescription
border sets all border properties in one declaration
border-collapse specifies whether or not table borders should be collapsed
border-spacing specifies distance between borders of adjacent cells
caption-side specifies placement of a table caption
empty-cells specifies whether or not to display borders and background on empty cells in a table
table-layout sets layout algorithm to be used for a table

CSS Layout: Display

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

display property specifies if/how an element is displayed.

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

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

Some block-level elements:


CSS Layout: max-width

Using width, max-width and margin:auto;

As mentioned before - 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, the margins can be set 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: A problem can happen with a <div> when the browser window is smaller than the width of the element. The browser will add a horizontal scrollbar to the page.

Using max-width in such a situation, will improve the browser's handling of small windows. This is important when making a site usable on small devices:
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:

Elements are then positioned using the properties:

However, these properties will not work unless the position property is set first. They also work differently depending on the position's value.

1. position:static;

HTML elements are positioned static by default.

Static positioned elements are not affected by the 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:

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

2. position:relative;

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

Setting:

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.

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

3. 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.
These 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.

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

4. position:absolute;

An element with position:absolute; is positioned relative to the nearest positioned ancestor - instead of positioned relative to the viewport, like fixed.

However, if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

📝 Note: A positioned element is one whose position is anything except static.

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

5. 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;.

📝 Note: Internet Explorer, Edge 15 and earlier versions do not support sticky positioning. Safari requires a -webkit-prefix (see example below). For sticky positioning to work use at least one of these properties:

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

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

6. Overlapping Elements

When elements are positioned, they can overlap other elements.

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

An element can have a positive or negative stack order:
img {
  position:absolute;
  left:0px;
  top:0px;
  z-index:-1;
}

An element with greater stack order is always in front of an element with a lower stack order.

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

7. Positioning Text In an Image

🚴 w3schools Examples: Positioning Text In an Image

All CSS Positioning Properties
PropertyDescription
bottom sets bottom margin edge for a positioned box
clip clips an absolutely positioned element
left sets left margin edge for a positioned box
position specifies type of positioning for an element
right sets right margin edge for a positioned box
top sets top margin edge for a positioned box
z-index sets the stack order of an element

CSS Layout - Overflow

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

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.

overflow property has the following values:

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

1. overflow:visible;

By default, the overflow is visible, meaning that it is not clipped and it renders outside the element's box:
div {
  width:200px;
  height:50px;
  background-color:#eee;
  overflow:visible;
}

2. overflow:hidden;

With the hidden value, the overflow is clipped, and the rest of the content is hidden:
div {
  overflow:hidden;
}

3. 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 not needed:
div {
  overflow:scroll;
}

4. overflow:auto;

The auto value is similar to scroll, but it adds scrollbars only when necessary:
div {
  overflow:auto;
}

5. overflow-x and overflow-y

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

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

All CSS Overflow Properties
PropertyDescription
overflow specifies what happens if content overflows an element's box
overflow-x specifies what to do with the left/right edges of the content if it overflows the element's content area
overflow-y specifies what to do with the top/bottom edges of the content if it overflows the element's content area

CSS Layout - float and clear

The float property specifies how an element should float.

The clear property specifies what elements can float beside the cleared element and on which side.

1. The float Property

float property is used for positioning and formatting content e.g. let an image float left to the text in a container.

float property can have one of the following values:

In its simplest use, the float property can be used to wrap text around images.

img {
  float:right;
}

2. The clear Property

clear property specifies what elements can float beside the cleared element and on which side.

clear property can have one of the following values:

The most common way to use the clear property is after the float property is used on an element.

When clearing floats, you should match clear to float:

The following example clears the float to the left - means that no floating elements are allowed on the left side of the div:

div {
  clear:left;
}

3. The clearfix Hack

If an element is taller than the element containing it, and it is floated, it will overflow outside of its container:

.clearfix {
  overflow:auto;
}

4. Float Examples

🚴 w3schools Float Examples

All CSS Float Properties
PropertyDescription
box-sizing defines how width and height of an element are calculated: should they include padding and borders, or not
clear specifies what elements can float beside the cleared element and on which side
float specifies how an element should float
overflow specifies what happens if content overflows an element's box
overflow-x specifies what to do with the left/right edges of the content if it overflows the element's content area
overflow-y specifies what to do with the top/bottom edges of the content if it overflows the element's content area

CSS Layout - display:inline-block

1. The display:inline-block Value

Compared to display:inline, the major difference is that display:inline-block allows setting width and height on an element:

Major difference between display:inline-block and display:block:

The following example shows the different behavior of:

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

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

.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

1. Center Align Elements

Use margin:auto; to horizontally center a block element - like <div>.

Setting the width of an element prevents 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:

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

2. Center Align Text

Use text-align:center; to just center the text inside an element.

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

3. Center an Image

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

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

4. Left and Right Align - Using position

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

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

5. Left and Right Align - Using float

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

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

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

6. The clearfix Hack

Can add overflow:auto; to the containing element to fix overflow outside of its container:

.clearfix {
  overflow:auto;
}

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

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

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

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

8. Center Vertically - Using line-height

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

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

9. Center Vertically - Using position & transform

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

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

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

📎 Tip: Learn more about transform property at 🎓 w3schools Advanced CSS 2D Transforms Chapter.

10. Center Vertically - Using Flexbox

Can use flexbox to center things.

📝 Note: flexbox is not supported in IE10 and earlier versions.


CSS Combinators

A combinator is something that explains the relationship between selectors.

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

There are four different combinators in CSS:

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

div p {
  background-color:yellow;
}

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

div > p {
  background-color:yellow;
}

3. Adjacent Sibling Selector

The adjacent sibling selector selects all elements that are the adjacent siblings of a specified element.

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

The following example selects all <p> elements that are placed immediately after <div> elements:

div + p {
  background-color:yellow;
}

4. General Sibling Selector

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

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

div ~ p {
  background-color:yellow;
}

All CSS Combinator Selectors
SelectorExampleExample Description
element element div p selects all <p> elements inside <div> elements
element>element div > p selects all <p> elements where the parent is a <div> element
element+element div + p selects all <p> elements that are placed immediately after <div> elements
element1~element2 p ~ ul selects every <ul> element that are preceded by a <p> element

CSS Pseudo-classes

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

For example, it can be used to:

1. Syntax

The syntax of pseudo-classes:

selector:pseudo-class {
  property:value;
}

2. Anchor Pseudo-classes

Links can be displayed in different ways:

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

3. Pseudo-classes and CSS Classes

Pseudo-classes can be combined with CSS classes.

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

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

4. Hover on <div>

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

div:hover {
  background-color:blue;
}

5. Simple Tooltip Hover

Hover over a <div> element to show a <p> element - like a tooltip:

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

div:hover p {
  display:block;
}

6. CSS - The :first-child Pseudo-class

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

6.1 Match the first <p> element

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

p:first-child {
  color: blue;
}

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

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

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

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

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

7. CSS - The :lang Pseudo-class

The :lang pseudo-class allows defining special rules for different languages.

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

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

All CSS Pseudo Classes
SelectorExampleExample Description
:active a:active selects the active link
:checked input:checked selects every checked <input> element
:disabled input:disabled selects every disabled <input> element
:empty p:empty selects every <p> element that has no children
:enabled input:enabled selects every enabled <input> element
:first-child p:first-child selects every <p> elements that is the first child of its parent
:first-of-type p:first-of-type selects every <p> element that is the first <p> element of its parent
:focus input:focus selects the <input> element that has focus
:hover a:hover selects links on mouse over
:in-range input:in-range selects <input> elements with a value within a specified range
:invalid input:invalid selects all <input> elements with an invalid value
:lang(language) p:lang(it) selects every <p> element with a lang attribute value starting with "it"
:last-child p:last-child selects every <p> elements that is the last child of its parent
:last-of-type p:last-of-type selects every <p> element that is the last <p> element of its parent
:link a:link selects all unvisited links
:not(selector) :not(p) selects every element that is not a <p> element
:nth-child(n) p:nth-child(2) selects every <p> element that is the second child of its parent
:nth-last-child(n) p:nth-last-child(2) selects every <p> element that is the second child of its parent, counting from the last child
:nth-last-of-type(n) p:nth-last-of-type(2) selects every <p> element that is the second <p> element of its parent, counting from the last child
:nth-of-type(n) p:nth-of-type(2) selects every <p> element that is the second <p> element of its parent
:only-of-type p:only-of-type selects every <p> element that is the only <p> element of its parent
:only-child p:only-child selects every <p> element that is the only child of its parent
:optional input:optional selects <input> elements with no "required" attribute
:out-of-range input:out-of-range selects <input> elements with a value outside a specified range
:read-only input:read-only selects <input> elements with a "readonly" attribute specified
:read-write input:read-write selects <input> elements with no "readonly" attribute
:required input:required selects <input> elements with a "required" attribute specified
:root root selects the document's root element
:target #news:target selects the current active #news element (clicked on a URL containing that anchor name)
:valid input:valid selects all <input> elements with a valid value
:visited a:visited selects all visited links

CSS Pseudo-elements

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

For example, it can be used to:

1. Syntax

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

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

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

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

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

📝 📝

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.

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

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:

4. Pseudo-elements and CSS Classes

Pseudo-elements can be combined with CSS classes:

/*will display the first letter of paragraphs with class="intro", in red and in a larger size.*/
p.intro::first-letter {
  color:#ff0000;
  font-size:200%;
}

5. Multiple Pseudo-elements

Several pseudo-elements can also be combined.

/*
-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
*/
p::first-letter {
  color:#ff0000;
  font-size:xx-large;
}

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

6. CSS - The ::before Pseudo-element

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

/*inserts an image before the content of each <h1> element*/
h1::before {
  content:url(smiley.gif);
}

7. CSS - The ::after Pseudo-element

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

/*inserts an image after the content of each <h1> element*/
h1::after {
  content:url(smiley.gif);
}

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

/*makes the selected text red on a yellow background*/
::selection {
  color:red;
  background:yellow;
}

All CSS Pseudo Elements
SelectorExampleExample Description
::after p::after insert content after every <p> element
::before p::before insert content before every <p> element
::first-letter p::first-letter selects the first letter of every <p> element
::first-line p::first-line selects the first line of every <p> element
::selection p::selection selects the portion of an element that is selected by a user

CSS Opacity/Transparency

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

🚴 w3schools CSS Opacity/Transparency Tutorial

There are 5 sections with examples explaining how to do:


CSS Navigation Bar

🚴 w3schools CSS Navigation Bar Tutorial

Navigation Bars

Having easy-to-use navigation is important for any web site.

With CSS you can transform boring HTML menus into good-looking navigation bars.

1. Navigation Bar = List of Links

A navigation bar uses standard HTML as a base.

The examples show how to build navigation bars from a standard HTML list.

2. CSS Vertical Navigation Bar

🚴 w3schools CSS Vertical Navigation Bar Tutorial

<style>
/* Step 1:
remove the bullets and the margins and padding from the list
makes a vertical nav bar*/
ul {
  list-style-type:none;
  margin:0;
  padding:0;
}

/* Step 2:
style the <a> elements inside the list
*/
li a {
  display:block;
  width:60px;
}
/*
display:block; - Displaying the links as block elements makes the whole link area clickable (not just the text), and it allows us to specify the width (and padding, margin, height, etc. if you want)
width:60px; - Block elements take up the full width available by default. We want to specify a 60 pixels width
*/
</style>

<!--sart with <ul> and <li> elements-->
<ul>
  <li><a href="default.asp">Home</a></li>
  <li><a href="news.asp">News</a></li>
  <li><a href="contact.asp">Contact</a></li>
  <li><a href="about.asp">About</a></li>
</ul>

2.1 Active/Current Navigation Link

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

.active {
  background-color:#4CAF50;
  color:white;
}

2.2 Center Links & Add Borders

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

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

ul {
  border:1px solid #555;
}

li {
  text-align:center;
  border-bottom:1px solid #555;
}

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

2.3 Full-height Fixed Vertical Navbar

Create a full-height, sticky side navigation:

ul {
  list-style-type:none;
  margin:0;
  padding:0;
  width:25%;
  background-color:#f1f1f1;
  height:100%; /* Full height */
  position:fixed; /* Make it stick, even on scroll */
  overflow:auto; /* Enable scrolling if the sidenav has too much content */
}

3. CSS Horizontal Navigation Bar

🚴 w3schools CSS Horizontal Navigation Bar Tutorial

There are two ways to create a horizontal navigation bar:

list items.

3.1 Inline List Items

One way to build a horizontal navigation bar is to specify the <li> elements as inline, in addition to the code from CSS Vertical Navigation Bar example:

/*
display: inline; - By default, <li> elements are block elements. Here, we remove the line breaks before and after each list item, to display them on one line
*/
li {
  display:inline;
}

3.2 Floating List Items

Another way of creating a horizontal navigation bar is to float the <li> elements, and specify a layout for the navigation links:

li {
  float:left;
}

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

📝 Note: If a !DOCTYPE is not specified, floating items can produce unexpected results.

Example explained:

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

4. Horizontal Navigation Bar Examples

/*
1. basic horizontal navigation bar
2. with a dark background color
3. change the background color of the links when the user moves the mouse over them
*/
ul {
  list-style-type:none;
  margin:0;
  padding:0;
  overflow:hidden;
  background-color:#333;
}

li {
  float:left;
}

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

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

4.1 Active/Current Navigation Link

/*
Add an "active" class to the current link to let the user know which page is showing:
*/
.active {
  background-color:#4CAF50;
}

4.2 Right-Align Links

<!--
Right-align links by floating the list items to the right (float:right;):
-->
<ul>
  <li><a href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li style="float:right"><a class="active" href="#about">About</a></li>
</ul>

4.3 Border Dividers

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

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

4.4 Fixed Navigation Bar

Make the navigation bar stay at the top or the bottom of the page, even when the user scrolls the page:
/*Fixed Top*/
ul {
  position:fixed;
  top:0;
  width:100%;
}

/*Fixed Bottom*/
ul {
  position:fixed;
  bottom:0;
  width:100%;
}

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

4.5 Gray Horizontal Navbar

/*gray horizontal navigation bar with a thin gray border*/
ul {
  border:1px solid #e7e7e7;
  background-color:#f3f3f3;
}

li a {
  color:#666;
}

4.6 Sticky Navbar

Add position:sticky; to <ul> to create a sticky navbar.

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

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

📝 Note: Internet Explorer, Edge 15 and earlier versions do not support sticky positioning. Safari requires a -webkit- prefix -see example above. Must also specify at least one of:

for sticky positioning to work.

5. More Examples

🚴 w3schools CSS Horizontal Navigation Bar Tutorial examples near bottom of page above ads



CSS Dropdowns

🚴 w3schools CSS Dropdowns Tutorial


CSS Image Gallery

🚴 w3schools CSS Image Gallery Tutorial

CSS can be used to create an image gallery.

Responsive Image Gallery


CSS Image Sprites

🚴 w3schools CSS Image Sprites Tutorial

An image sprite is a collection of images put into a single image.

A web page with many images can take a long time to load and generates multiple server requests.

Using image sprites will reduce the number of server requests and save bandwidth.


CSS Attribute Selectors

1. Style HTML Elements With Specific Attributes

It is possible to style HTML elements with attributes.

2. CSS [attribute] Selector

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

/* select all <a> elements with a target attribute */
a[target] {
  background-color:yellow;
}

3. CSS [attribute="value"] Selector

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

/* select all <a> elements with a target="_blank" attribute */
a[target="_blank"] {
  background-color:yellow;
}

4. CSS [attribute~="value"] Selector

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

/*
select all elements with a title attribute that contains a space-separated list of words, one of which is "flower"

will match elements with title="flower", title="summer flower", and title="flower new", but not title="my-flower" or title="flowers"
*/
[title~="flower"] {
  border:5px solid yellow;
}

5. CSS [attribute|="value"] Selector

The [attribute|="value"] selector is used to select elements with the specified attribute starting with the specified value.

/*
select all elements with a class attribute value that begins with "top"

*** Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text"! 
*/
[class|="top"] {
  background:yellow;
}

6. CSS [attribute^="value"] Selector

The [attribute^="value"] selector is used to select elements whose attribute value begins with a specific value.

/*
select all elements with a class attribute value that begins with "top"

*** Note: The value does not have to be a whole word! 
*/
[class^="top"] {
  background:yellow;
}

7. CSS [attribute$="value"] Selector

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

/*
select all elements with a class attribute value that ends with "test"

*** Note: The value does not have to be a whole word!  
*/
[class$="test"] {
  background:yellow;
}

8. CSS [attribute*="value"] Selector

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

/*
select all elements with a class attribute value that contains "te"

*** Note: The value does not have to be a whole word!  
*/
[class*="te"] {
  background:yellow;
}

9. Styling Forms

/* attribute selectors can be useful for styling forms without class or ID */
input[type="text"] {
  width:150px;
  display:block;
  margin-bottom:10px;
  background-color:yellow;
}

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

📎 Tip: Visit 🚴 w3schools CSS Forms Tutorial for more examples on how to style forms with CSS.

All CSS Attribute Selectors
SelectorExampleExample Description
[attribute] [target] selects all elements with a target attribute
[attribute=value] [target=_blank] selects all elements with target="_blank"
[attribute~=value] [title~=flower] selects all elements with a title attribute containing the word "flower"
[attribute|=value] [lang|=en] selects all elements with a lang attribute value starting with "en"
[attribute^=value] a[href^="https"] selects every <a> element whose href attribute value begins with "https"
[attribute$=value] a[href$=".pdf"] selects every <a> element whose href attribute value ends with ".pdf"
[attribute*=value] a[href*="w3schools"] selects every <a> element whose href attribute value contains the substring "w3schools"

CSS Forms

The look of a HTML form can be greatly improved with CSS

.

1. Styling Input Fields

/* this width property determines width of all input fields */
input {
  width:100%;
}

Examples of styling specific input types using attribute selectors:

2. Padded Inputs

/*
padding property adds space inside the text field

*** Tip: if many inputs after each other, can add some margin, to separate them more
*/
input[type=text] {
  width:100%;
  padding:12px 20px;
  margin:8px 0;
  box-sizing:border-box;
}

📝 Note: In the above example, the box-sizing property is set to border-box. This makes sure that the padding and eventually borders are included in the total width and height of the elements. Read more about the box-sizing property at 🎓 w3schools Advanced CSS Box Sizing Tutorial

3. Bordered Inputs

/*
Use the border property to change the border size and color
use the border-radius property to add rounded corners
*/
input[type=text] {
  border:2px solid red;
  border-radius:4px;
}

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

4. Colored Inputs

/*
Use background-color property to add a background color to the input
use the color property to change the text color
*/
input[type=text] {
  background-color:#3CBC8D;
  color:white;
}

5. Focused Inputs

By default, some browsers will add a blue outline around the input when it gets focus clicked on. You can remove This behavior can be removed by adding outline:none; to the input.

/*
Use the :focus selector to do something with the input field when it gets focus
*/
input[type=text]:focus {
  background-color:lightblue;
}
/* or */
input[type=text]:focus {
  border:3px solid #555;
}

6. Input with icon/image

If you want an icon inside the input, use the background-image property and position it with the background-position property. Also notice a large left padding was added to reserve the space of the icon:

input[type=text] {
  background-color:white;
  background-image:url('searchicon.png');
  background-position:10px 10px;
  background-repeat:no-repeat;
  padding-left:40px;
}

7. Animated Search Input

/* use transition property to animate width of the search input area when it 
gets focus */ 
input[type=text] {
  transition:width 0.4s ease-in-out;
}

input[type=text]:focus {
  width:100%;
}

Learn more about transition property at 🎓 w3schools Advanced CSS Transitions Tutorial

8. Styling Textareas

📎 Tip: Use the resize property to prevent textareas from being resized disables grabber at the bottom right corner of the textarea.

textarea {
  width:100%;
  height:150px;
  padding:12px 20px;
  box-sizing:border-box;
  border:2px solid #ccc;
  border-radius:4px;
  background-color:#f8f8f8;
  resize:none;
}

9. Styling Select Menus

can size attrubute be set through css?

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

10. Styling Input Buttons

/* Tip: use width:100% for full-width buttons */
input[type=button], input[type=submit], input[type=reset] {
  background-color:#4CAF50;
  border:none;
  color:white;
  padding:16px 32px;
  text-decoration:none;
  margin:4px 2px;
  cursor:pointer;
}

Read more about how to style buttons with CSS at 🎓 w3schools Advanced CSS Buttons Tutorial

11. Responsive Form

When resizing browser window due to device size or user actions form layout can be adjusted to look better.

Advanced: Read about using media queries to create a responsive form at 🎓 w3schools Advanced CSS Media Queries Tutorial


CSS Counters

CSS counters are variables maintained by CSS whose values can be incremented by CSS rules - to track how many times they are used. Counters allow adjusting the appearance of content based on its placement in the document.

1. Automatic Numbering With Counters

To work with CSS counters use the following properties:

To use a CSS counter, it must first be created with counter-reset.

The following example creates a counter for the page in the body selector, then increments the counter value for each <h2> element and adds Section <value of the counter>: to the beginning of each <h2> element:

body {
  counter-reset:section;
}

h2::before {
  counter-increment:section;
  content:"Section " counter(section) ": ";
}

2. Nesting Counters

The following example creates one counter for the page section and one counter for each <h1> element subsection. The section counter will be counted for each <h1> element with Section <value of the section counter>., and the subsection counter will be counted for each <h2> element with <value of the section counter>.<value of the subsection counter>:

body {
  counter-reset:section;
}

h1 {
  counter-reset:subsection;
}

h1::before {
  counter-increment:section;
  content:"Section " counter(section) ". ";
}

h2::before {
  counter-increment:subsection;
  content:counter(section) "." counter(subsection) " ";
}

A counter can also be useful to make outlined lists because a new instance of a counter is automatically created in child elements. Here counters() function is used to insert a string between different levels of nested counters:

ol {
  counter-reset:section;
  list-style-type:none;
}

li::before {
  counter-increment:section;
  content:counters(section,".") " ";
}

CSS Counter Properties
PropertyDescription
content used with the ::before and ::after pseudo-elements, to insert generated content
counter-increment increments one or more counter values
counter-reset creates or resets one or more counters

CSS Website Layout

🚴 w3schools CSS Website Layout Tutorial


CSS Units

CSS has several different units for expressing a length.

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

📝 Note: A whitespace cannot appear between the number and the unit.

However, if the value is 0, the unit can be omitted.

For some CSS properties, negative lengths are allowed.

There are two types of length units:

1. Absolute Lengths

The absolute length units are fixed and a length expressed in any of these will appear as exactly that size.

Absolute length units are not recommended for use on screen, because screen sizes vary so much. However, they can be used if the output medium is known, such as for print layout.

UnitDescription
cm centimeters
mm millimeters
in inches 1in = 96px = 2.54cm
px Note 1 pixels 1px = 1/96th of 1in
pt points 1pt = 1/72 of 1in
pc picas 1pc = 12 pt

📝 Note 1: Pixels px are relative to the viewing device. For low-dpi devices, 1px is one device pixel dot of the display. For printers and high resolution screens 1px implies multiple device pixels.

2. Relative Lengths

Relative length units specify a length relative to another length property. Relative length units scales better between different rendering mediums.

UnitDescription
em relative to the font-size of the element - 2em means 2 times the size of the current font
ex relative to the x-height of the current font - rarely used
ch relative to width of the 0 zero
rem relative to font-size of the root element
vw relative to 1% of the width of the viewport Note 2
vh relative to 1% of the height of the viewport Note 2
vmin relative to 1% of viewport's Note 2 smaller dimension
vmax relative to 1% of viewport's Note 2 larger dimension
% relative to the parent element

📎 Tip: The em and rem units are practical in creating perfectly scalable layout!

📝 Note 2: Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm.


CSS Specificity

1. What is Specificity?

If there are two or more conflicting CSS rules that point to the same element, the browser follows some rules to determine which one is most specific and therefore wins out.

Specificity is a score/rank that determines which style declarations are ultimately applied to an element.

The universal selector * has low specificity, while ID selectors are highly specific!

📝 Note: Specificity is a common reason why CSS rules don't apply to some elements in the order desired.

2. Specificity Hierarchy

Every selector has its place in the specificity hierarchy.

There are four categories which define the specificity level of a selector:
CategoryDescriptionExample
Inline styles an inline style is attached directly to the element to be styled <h1 style="color: #ffffff;">
IDs an ID is a unique identifier for the page elements #navbar.
Classes, attributes and pseudo-classes this category includes:
  • .classes
  • [attributes]
  • pseudo-classes
:hover
:focus
Elements and pseudo-elements this category includes:
  • element
  • names
  • pseudo-elements
h1
div
:before
:after

3. How to Calculate Specificity?

Memorize how to calculate specificity!

There are 5 steps to calculating specificity:

  1. Start at 0
  2. add 1000 for style attribute
  3. add 100 for each ID
  4. add 10 for each attribute, class or pseudo-class
  5. add 1 for each element name or pseudo-element

Consider these three code fragments:
 Code FragmentSpecificityCategory
A h1 1 one element
B #content h1 101 one ID reference and one element
C <div id="content">
    <h1 style="color:#ffffff">Heading</h1>
</div>
1000 inline styling
Since 1 < 101 < 1000, the third rule C has a greater level of specificity, and therefore will be applied.

4. Specificity Rules

Equal specificity: the latest rule counts.

If the same rule is written twice in the external style sheet, then the lower rule in the style sheet is closer to the element to be styled, and therefore will be applied.
Example:

h1 {background-color:yellow;}
h1 {background-color:red;} /*this rule is always applied.*/

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

/*this rule is more specific than other two therefore it will be used*/
div#a {
  background-color:green;
}

#a {
  background-color:yellow;
}

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

Contextual selectors are more specific than a single element selector.

The embedded <style></style> is closer to the element than an external CSS file for any elements being styled. Therefore in the following situation:

From external CSS file:

#content h1 {
  background-color:red;
}

In HTML file:

<style>
#content h1 {
  background-color:yellow; /*this rule will be applied*/
}
</style>

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

/* .intro rule beats h1 rule */
.intro {
  background-color:yellow;
}
 
h1 {
  background-color:red;
}

The universal selector and inherited values have a specificity of 0    * , body * and similar have zero specificity. Inherited values also have a specificity of 0.


🏆 🎈 The End!!! 🏁 📣
-