facebook twitter
Webucator's Free Introduction to CSS Tutorial

Lesson: Crash Course in CSS

Welcome to our free Introduction to CSS tutorial. This tutorial is based on Webucator's Introduction to CSS Training course.

In this lesson, you will receive a crash course in the uses of CSS.

Lesson Goals

  • Understand the benefits of Cascading Style Sheets.
  • Use styles to redefine how elements are formatted.
  • Understand and use different CSS selectors.
  • Understand and use CSS combinators to narrow CSS selections.
  • Understand the CSS Cascade.
  • Understand and use CSS Resets.
  • Understand and use CSS Normalizers.
  • Use external stylesheets, embedded stylesheets, and inline styles.
  • Use <div> and <span> elements.
  • Understand different media types.
  • Understand and use the viewport meta tag.
  • Use the different units of measurement available in CSS.
  • Understand how browsers style pages.
  • Understand inheritance.

Benefits of Cascading Style Sheets

Since HTML 4.0, most HTML formatting elements (e.g., u for underline) and attribute (e.g., bgcolor for background color) have been deprecated, meaning that, although they may still be supported by browsers, the World Wide Web Consortium (W3C) recommends that they no longer be used. Web designers are to use CSS instead.

The major benefits of CSS are:

  1. Cleaner Code
    • Easier to maintain.
    • Speedier download.
    • Better for search engine optimization.
  2. Modular Code
    • Style rules can be applied to multiple pages.
    • Consistency of design.
    • Easier to maintain.
  3. Design Power
    • Precise control of position, size, margins, etc.
  4. Division of Labor
    • Developers develop / Designers design.
  5. Better Accessibility (see https://www.w3.org/TR/CSS-access)
    • No need to misuse tags (e.g., <blockquote> for formatting).
    • No need for invisible images for positioning.
    • Users' stylesheets override authors' styles.

CSS Rules

CSS rules are statements that define the style of an element or group of elements. The syntax is as follows:

Syntax

selector {
	property: value;
	property: value;
	property: value;
}
p {
	color: darkgreen;
	font-family: Verdana;
	font-size: 1.5em;
}

This rule specifies that all paragraph text should be darkgreen and use a 1.5em Verdana font.

CSS Comments

Comments in CSS begin with "/*" and end with "*/". See the example below:

p {
	color: red; /* All paragraphs should be red */
}

Selectors

There are several types of selectors:

  1. Type
  2. Class
  3. ID
  4. Attribute
  5. Universal

Selectors identify the element(s) affected by the CSS rule.

Type Selectors

Type selectors specify elements by tag name and affect every instance of that element type. Looking again at a previous example:

p {
	color: darkgreen;
	font-family: Verdana;
	font-size: 1.5em;
}

This rule specifies that the text of every p element should be darkgreen and use a 1.5em Verdana font.

Class Selectors

In HTML, all elements can take the class attribute, which assigns a class name to an element. The names given to classes are arbitrary, but should be descriptive of the purpose of the class. In CSS, class selectors begin with a dot. For example, the following rule creates a class called "warning," which makes the text of all elements of that class bold and red:

.warning {
	color: red;
	font-weight: bold;
}

Following are a couple of examples of elements of the "warning" class:

<h1 class="warning">WARNING</h1>
<p class="warning">Don't go there!</p>

If the class selector is preceded by an element name, then that selector only applies to the specified type of element. To illustrate, the following two rules indicate that h1 elements of the class "warning" will be underlined, while p elements of the class "warning" will not be:

h1.warning {
	color: red;
	text-decoration: underline;
}

p.warning {
	color: red;
	font-weight: bold;
}

Because both rules indicate that the color should be red, this could be rewritten as follows:

.warning {
	color: red;
}

h1.warning {
	text-decoration: underline;
}

p.warning {
	font-weight: bold;
}

Note that you can assign an element any number of classes simply by separating the class names with spaces like this:

Syntax

<div class="class1 class2 class3">...

ID Selectors

As with the class attribute, in HTML, all elements can take the id attribute, which is used to uniquely identify an element on the page. In CSS, ID selectors begin with a number sign (#) and have arbitrary names. The following rule will give the element with the "main-text" id a margin of 1.2em on the left and right:

#main-text {
	margin-left: 1.2em;
	margin-right: 1.2em;
}

<div id="main-text">
	This is the main text of the page...
</div>

Attribute Selectors

Attribute selectors specify elements that contain a specific attribute. They can also specify the value of that attribute.

The following selector affects all links with a target attribute:

a[target] {
	color: red;
}

The following selector would only affect links whose target attribute is exactly "_blank":

a[target='_blank'] {
	color: red;
}

The following selector will only affect links whose href attribute starts with "mailto":

a[href^='mailto'] {
	color: red;
}

The following selector will only affect links whose class attribute ends with "link":

a[class$='link'] {
	color: red;
}

The following selector will only affect links whose class attribute contains "top":

a[href*='top'] {
	color: red;
}

The Universal Selector

The universal selector is an asterisk (*). It matches every element.

* {
	color: red;
}

Grouping

Selectors can share the same declarations by separating them with commas. The following rule will underline all i elements, all elements of the class "warning" and the element with the id of "important":

i,
.warning,
#important {
	text-decoration: underline;
}

Combinators

Combinators allow for the selection of elements based on the relationships between selectors.

There are several types of combinators:

  1. Descendant
  2. Child
  3. General sibling
  4. Adjacent sibling

Descendant Combinators

Descendant combinators specify elements by ancestry. Each "generation" is separated by a space. For example, the following rule states that strong elements within p elements should have red text:

p strong {
	color: red;
}

With descendant selectors, generations can be skipped. In other words, the code above does not require that the strong element is a direct child of the p element.

Child Combinators

Child combinators specify a direct parent-child relationship. They are indicated by placing a > sign between the two element names:

p > strong {
	color: red;
}

In this case only strong elements that are direct children of p elements are affected.

General Sibling Combinators

General sibling combinators specify a sibling relationship (children of the same parent element) between two elements where the second element specified comes after the first. They are indicated by placing a ~ sign between the two element names:

em ~ strong {
	color: red;
}

In this case only strong elements that are siblings of and follow em elements are affected. For example, in the following code: both strong elements would be red:

<em>Hello!</em>
<strong>Hi there!</strong>
I'm not in a strong or em element.
<strong>Howdy!</strong>

Adjacent Sibling Combinators

Adjacent sibling combinators specify a sibling relationship (children of the same parent element) between two elements where the second element specified comes immediately after the first. They are indicated by placing a + sign between the two element names:

em + strong {
	color: red;
}

In this case only strong elements that are siblings of and immediately follow em elements are affected. In the HTML code shown above, only the first strong element (with the text "Hi there!") would be red.

Precedence of Selectors

In the event that rules conflict:

  • The rule with the more specific selector takes precedence.
  • In the event that two selectors have the same specificity, the rule specified later in the document takes precedence.

!important

Adding !important to any CSS declaration will give that declaration the highest specificity, but please note that using !important is bad practice, and should be avoided. See https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity#The_!important_exception for more information.

How Browsers Style Pages

Browsers have style pages to make them readable by default (i.e., without CSS). Without any styles, an HTML page would just be one big line of text. For example, look at the code below:

Code Sample:

CrashCourse/Demos/default-styles.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Default Styles</title>
</head>
<body>
  <h1>Header 1</h1>
  <h2>Header 2</h2>
  <h3>Header 3</h3>
  <h4>Header 4</h4>
  <p>This is a paragraph.</p>
  <div>This is a div element that contains 
    <a href="http://www.runners-home.com">a link to Runners Home</a>.
  </div>
  <ul>
    <li>List Item</li>
    <li>List Item</li>
    <li>List Item</li>
  </ul>
  <ol>
    <li>List Item</li>
    <li>List Item</li>
    <li>List Item</li>
  </ol>
</body>
</html>

Code Explanation

To make pages readable by default, the browsers add styles to render the page like this:Default Styles

Notice the default styles:

  1. The headings are bold, have varying font sizes, and have margin before and after them.
  2. All of the elements, except the link, are on their own blocks as if they had <br> tags before and after them.
  3. The unordered and ordered lists come with bullets and numbers, respectively.
  4. The link is blue and underlined.

It is important to recognize that browsers add default styles to HTML pages because often you will use CSS to add to or override these default styles.

CSS Resets

CSS resets are used to remove most default styles that browsers add to HTML elements, so that designers can decide on these styles themselves. For example, header tags will no longer be big and bold. By resetting the default styles, the designer gets rid of inconsistencies between browser default styles, opening the door for them to add styles that are rendered the same by all browsers.

A common CSS reset is the Meyer Reset, which you can see below:

Code Sample:

CrashCourse/Demos/reset.css
/* http://meyerweb.com/eric/tools/css/reset/ 
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
  display: block;
}
body {
  line-height: 1;
}
ol, ul {
  list-style: none;
}
blockquote, q {
  quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}

Code Explanation

Attaching this stylesheet to default-styles.html will render the page like this:Reset Styles

CSS Normalizers

CSS normalizers are slightly different from CSS resets. Instead of getting rid of all styles, they adjust styles so that they are consistent between browsers. In doing so, normalizers have to choose some styles over others. As such, normalizers are opinionated, meaning that the authors of these normalizers have made design choices based on their own preferences. For the rest of this course, we will be using a slightly modified version of a normalizer called normalize.css in all of our files.

Normalize

normalize.css is the normalizer used by Bootstrap to improve cross-browser rendering.

External Stylesheets, Embedded Stylesheets, and Inline Styles

External Stylesheets

External stylesheets are created in separate documents with a ".css" extension. An external stylesheet is simply a listing of rules. It cannot contain HTML tags. Throughout this course, we will mainly be working with external stylesheets. CrashCourse/Demos/styles.css is an example of an external stylesheet.

Code Sample:

CrashCourse/Demos/styles.css
.warning {
  color: red;
}

h1.warning {
  text-decoration: underline;
}

p.warning {
  font-weight: bold;
}

Code Explanation

The above CSS file can be included in any number of HTML pages. The <link> tag, which usually goes in the head of an HTML page, is used to link to an external stylesheet.

<link> Attributes
Attributed Description
href points to the location of the external stylesheet
rel must be set to "stylesheet" for linking stylesheets

Notice the <link> tag in the code below that links to styles.css:

Code Sample:

CrashCourse/Demos/external-stylesheet.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="../normalize.css" rel="stylesheet">
<link href="styles.css" rel="stylesheet">
<title>External Stylesheet</title>
</head>
<body class="webucator">
  <h1 class="warning">WARNING</h1>
  <p class="warning">Don't go there!</p>
</body>
</html>

Code Explanation

This page will render as follows: External Stylesheet

There is no limit to the number of external stylesheets a single HTML page can use. Also, external stylesheets can be combined with embedded stylesheets and inline styles.

Embedded Stylesheets

Embedded stylesheets appear in the style element, which usually goes in the head of an HTML page. The code below shows a page with an embedded stylesheet:

Code Sample:

CrashCourse/Demos/embedded-stylesheet.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="../normalize.css" rel="stylesheet">
<style>
  .warning {
    color: red;
  }

  h1.warning {
    text-decoration: underline;
  }
  
  p.warning {
    font-weight: bold;
  }
</style>
<title>Embedded Stylesheet</title>
</head>
<body class="webucator">
  <h1 class="warning">WARNING</h1>
  <p class="warning">Don't go there!</p>
</body>
</html>

Code Explanation

This page will render the same as the HTML page with the external stylesheet.

Inline Styles

Inline styles are created by adding the style attribute to a tag. As with the class and id attributes, all elements can take the style attribute. The value of the style attribute is a list of one or more declarations separated by semicolons. The code sample below illustrates how inline styles are used:

Code Sample:

CrashCourse/Demos/inline-styles.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="../normalize.css" rel="stylesheet">
<title>Inline Styles</title>
</head>
<body class="webucator">
  <p style="color: blue; font-style: italic; font-size: 1em;">
    Common Greetings
  </p>
  <ul style="border: red; font-size: 0.8em;">
    <li style="list-style-type: square;">Hello</li>
    <li style="list-style-type: circle;">Hi</li>
    <li style="list-style-type: disc;">Howdy</li>
  </ul>
</body>
</html>

Code Explanation

This page will render as follows:Inline Styles Common Greetings

Please note that it is bad practice to use inline styles in production code; however, they can be useful for testing and debugging.

Creating an External Stylesheet

Duration: 25 to 40 minutes.

In this exercise, you will add several simple rules to an external stylesheet and link to it from CrashCourse/Exercises/index-external-styles.html.

Do not worry about learning the CSS properties and values at this point. There will be some we have not yet introduced. This exercise is just to give you some practice creating a stylesheet.

  1. Open CrashCourse/Exercises/index.html in a browser. It should look like this: Home Runs Without Styles
  2. Open CrashCourse/Exercises/index.html in your editor and save it as index-external-styles.html.
  3. Create a new file and save it as styles.css in the same directory.
  4. Add a <link> tag with an href value of "styles.css" and a rel value of "stylesheet" in the head of index-external-styles.html.
  5. In styles.css, add a rule for the body element that contains the following declarations:
    • background-attachment: fixed;
    • background-image: url(images/baseball.png);
    • background-position: bottom;
    • background-repeat: repeat-x;
  6. Add a rule for table elements that contains the following declarations:
    • background-color: white;
    • border-collapse: collapse;
    • margin: auto;
    • min-width: 800px;
  7. Add a rule for caption elements that contains the following declaration:
    • font-style: italic;
  8. Add a rule for thead elements that contains the following declarations:
    • background-color: darkblue;
    • color: white;
  9. Add a rule for td and th elements that contains the following declarations:
    • border: 1px solid orange;
    • margin: 0;
    • padding: .3em;
  10. Add a rule for td elements that are in the tfoot that contains the following declarations:
    • background-color: silver;
    • border-top: 2px solid black;
    • font-weight: bold;
  11. Add a rule for elements with the "steroids-era" class that contains the following declaration:
    • font-style: italic;
  12. Add a rule for the element with the "key" id that contains the following declarations:
    • background-color: lightgray;
    • font-style: italic;
  13. Add the following two rules to the bottom of styles.css:
    tr td:nth-child(2) {
      text-align: center;
    }
    
    .steroids-era td:first-child::after {
      content: '*';
    }
  14. In index-external-styles.html:
    1. Assign a class of "steroids-era" to the table rows containing Barry Bonds and Alex Rodriguez.
    2. Assign an id of "key" to the second table row in the tfoot.
  15. Open index-external-styles.html in a browser. It should look like this: Stylesheet Rendered

Solution:

CrashCourse/Solutions/index-external-styles.html
---- C O D E   O M I T T E D ----
<link href="styles.css" rel="stylesheet">
<title>Home Run Hitters</title>
</head>
<body class="webucator">
  <table>
    <caption>All-time Home Run Records</caption>
    <thead>
      <tr>
        <th>Player</th>
        <th>Home Runs</th>
        <th>Team</th>
      </tr>
    </thead>
    <tbody>
      <tr class="steroids-era">
        <td>Barry Bonds</td>
        <td>762</td>
        <td>Giants</td>
      </tr>
---- C O D E   O M I T T E D ----
      <tr class="steroids-era">
        <td>Alex Rodriguez</td>
        <td>696</td>
        <td>Yankees</td>
      </tr>
---- C O D E   O M I T T E D ----
      <tr>
        <td colspan="3" id="key">*Steroids Era</td>
      </tr>
    </tfoot>
  </table>
</body>
</html>

Solution:

CrashCourse/Solutions/styles.css
body {
  background-attachment: fixed;
  background-image: url(images/baseball.png);
  background-position: bottom;
  background-repeat: repeat-x;
}

table {
  background-color: white;
  border-collapse: collapse;
  margin: auto;
  min-width: 800px;
}

caption {
  font-style: italic;
}

thead {
  background-color: darkblue;
  color: white;
}

td,
th {
  border: 1px solid orange;
  margin: 0;
  padding: .3em;
}

tfoot td {
  background-color: silver;
  border-top: 2px solid black;
  font-weight: bold;
}

.steroids-era {
  font-style: italic;
}

#key {
  background-color: lightgray;
  font-style: italic;
}

tr td:nth-child(2) {
  text-align: center;
}

.steroids-era td:first-child::after {
  content: '*';
}

Creating an Embedded Stylesheet

Duration: 5 to 10 minutes.

In this exercise, you will replace your external stylesheet with an embedded stylesheet.

  1. Open CrashCourse/Exercises/index-external-styles.html in your editor and save it as index-embedded-styles.html.
  2. Remove the <link> tag, and add a style block.
  3. Copy and paste all the CSS rules from styles.css to the style block in index-embedded-styles.html.
  4. Open index-embedded-styles.html in a browser. It should look the same as index-external-styles.html did.

Solution:

CrashCourse/Solutions/index-embedded-styles.html
---- C O D E   O M I T T E D ----
<title>Home Run Hitters</title>
<style>
  body {
    background-attachment: fixed;
    background-image: url(images/baseball.png);
    background-position: bottom;
    background-repeat: repeat-x;
  }
  
  table {
    background-color: white;
    border-collapse: collapse;
    margin: auto;
    min-width: 800px;
  }
  
  caption {
    font-style: italic;
  }
  
  thead {
    background-color: darkblue;
    color: white;
  }
  
  td,
  th {
    border: 1px solid orange;
    margin: 0;
    padding: .3em;
  }
  
  tfoot td {
    background-color: silver;
    border-top: 2px solid black;
    font-weight: bold;
  }
  
  .steroids-era {
    font-style: italic;
  }
  
  #key {
    background-color: lightgray;
    font-style: italic;
  }
  
  tr td:nth-child(2) {
    text-align: center;
  }
  
  .steroids-era td:first-child::after {
    content: '*';
  }
</style>
</head>
---- C O D E   O M I T T E D ----

Adding Inline Styles

Duration: 10 to 20 minutes.

In this exercise, you will add some inline styles.

  1. Open CrashCourse/Exercises/index-external-styles.html and save it as index-inlines-styles.html.
  2. Add inline styles to the table data cells containing the word "Giants". The style should contain the following declarations:
    • color: darkred;
    • font-style: italic;
  3. Add an inline style to the table data cell containing the word "Braves". The style should contain the following declarations:
    • color: red;
    • font-style: italic;
  4. Add an inline style to the table data cells containing the word "Yankees". The style should contain the following declarations:
    • color: navy;
    • font-style: italic;
  5. Open index-inline-styles.html in a browser. The last column should now look like this:Inline Styles Rendered

Solution:

CrashCourse/Solutions/index-inline-styles.html
---- C O D E   O M I T T E D ----

    <tbody>
      <tr class="steroids-era">
        <td>Barry Bonds</td>
        <td>762</td>
        <td style="color: darkred; font-style: italic;">Giants</td>
      </tr>
      <tr>
        <td>Hank Aaron</td>
        <td>755</td>
        <td style="color: red; font-style: italic;">Braves</td>
      </tr>
      <tr>
        <td>Babe Ruth</td>
        <td>714</td>
        <td style="color: navy; font-style: italic;">Yankees</td>
      </tr>
      <tr class="steroids-era">
        <td>Alex Rodriguez</td>
        <td>696</td>
        <td style="color: navy; font-style: italic;">Yankees</td>
      </tr>
      <tr>
        <td>Willie Mays</td>
        <td>660</td>
        <td style="color: darkred; font-style: italic;">Giants</td>
      </tr>
    </tbody>
---- C O D E   O M I T T E D ----

<div> and <span>

The <div> and <span> tags are used in conjunction with Cascading Style Sheets. By themselves, they do very little. In fact, the <span> tag has no visual effect on its contents. The only effect of the <div> tag is to block off its contents, similar to putting a <br> tag before and after a section on the page.

Like all tags, the <div> and <span> tags can take the class, id, and style attributes. It is through these attributes that styles are applied to the elements. Unlike p (paragraph) elements, main (main content) elements, header (header content) elements, etc., div elements and span elements do not inherently represent anything. div elements are generic content containers for flow content and span elements are generic containers of inline elements.

Code Sample:

CrashCourse/Demos/div-and-span.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
  div {
    border-color: blue;
    border-style: groove;
    border-width: 2em;
    font-family: Verdana;
    font-size: 1em;
    padding: .5em;
  }

  span {
    color: red;
    font-style: italic;
  }
</style>
<title>Div and Span</title>
</head>
<body class="webucator">
<div>
  <p>
    All of this text is in a div, but 
    <span>this text is also in a span</span>.
  </p>
</div>
</body>
</html>

Code Explanation

This page will render as follows:div and span

Divs and Spans

Duration: 10 to 20 minutes.

In this exercise, you will add class and id attributes to <div> and <span> tags to an already existing HTML page. Open ClassFiles/CrashCourse/divs-and-spans.html and ClassFiles/CrashCourse/styles-divs-spans.css in your editor. You will need to modify the HTML page based on the code in the CSS page. You will not need to modify the CSS page. Your goal is to make the page render as follows:Divs and Spans

There are no step-by-step instructions. Review the rules in the external stylesheet and apply classes and ids as appropriate.

Solution:

CrashCourse/Solutions/divs-and-spans.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="../normalize.css" rel="stylesheet">
<link href="styles-divs-spans.css" rel="stylesheet">
<title>Divs and Spans</title>
</head>
<body class="webucator">
<div id="top-div">
  <span class="left-span">1</span>
  <span class="mid-span">2</span>
  <span class="right-span">3</span>
</div>
<div id="mid-div">
  <span class="left-span">4</span>
  <span class="mid-span">5</span>
  <span class="right-span">6</span>
</div>
<div id="bottom-div">
  <span class="left-span">7</span>
  <span class="mid-span">8</span>
  <span class="right-span">9</span>
</div>
</body>
</html>

Media Types

Styles can be defined for different media. For example, you may want to style a page one way for viewing with a browser and a different way for viewing in print. Some possible media types are:

  • all
  • print
  • screen
  • speech

To define the media type for an entire external or embedded stylesheet, the media attribute is added to the <link> or <style> tag, and assigned the value of a media type. If the media attribute is not included, the media type defaults to all.

Syntax

<link href="stylesheet.css" rel="stylesheet media="screen">
        
<style media="all"> 
  /* rules */
</style>

It is also possible to target multiple media types within one stylesheet using @media.

Syntax

@media screen {
  /* rules */
}
        
@media print {
  /* rules */
}

@media is a powerful CSS tool, and we will later look at how it can be used to target not just the type of media but also aspects of the user's device: screen width, screen height, orientation, etc. This is done with media queries. Media queries allow us to craft pages that are responsive, presenting different layouts for desktop computers, tablet devices, and smartphones.

The viewport meta tag

You may have noticed that all of our files have a line of code in the head that looks like this:

<meta name="viewport" content="width=device-width,initial-scale=1">

This is called the viewport meta tag and it is used to help pages adjust correctly for all devices. For more information see https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag.

Units of Measurement

CSS allows for the use of many different units when specifying property values such as font size, border size, margins, etc. However, standards have been established to decide what units to use for different media types. In this course, except where specifically stated, you will be designing for screen.

Note that units of measurement and sizing will be covered throughout the course. In this section, we provide a general overview of the different units of measurement.

Absolute vs. Relative Units

Absolute units have a basis in the physical world, although their actual size on the screen depends on the resolution and size of the user's device. When designing for screen, it is standard to use pixels for absolute units.

Relative units are relative to the size of other things (e.g., window size, font size, container element size, etc.). When designing for screen, it is standard to use ems, rems, and percentages for relative units.

Pixels

Pixels are the only recommended absolute unit to be used when designing for screen. A common practice is to use pixels to set root font sizes for different screen and window sizes. Root font sizes are font sizes set on the html or body element. This allows for designs using mostly ems and rems to adjust between different screen and window sizes because ems and rems are relative to font size.

Ems and Rems

It is recommended to use ems and rems for almost everything when building responsive designs for screens. The exception to this rule is widths, which are more often defined in pixels or percentages. An em is the size of the font size for the current element or the parent element. For example, if the font-size of the html element is set to 14px, then for all elements within that html element, 1em is 14px.

Rems are similar to ems, except for one key difference. The 'r' in rem stands for 'root' because 1rem is always equal to the root font size (the font size set for the html element) regardless of what element it is in. This means 1rem is consistent throughout the page, while 1em is not. Both ems and rems can be used to accomplish the same things.

The code below illustrates the difference between ems and rems:

Code Sample:

CrashCourse/Demos/ems-vs-rems.html
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="../normalize.css" rel="stylesheet">
<style>
  /* Tighten vertical spacing of headings. */
  h1,
  h2,
  h3 {
    margin-bottom: .2rem; 
    margin-top: .2rem; 
  } 
</style>
<title>Ems vs Rems</title>
</head>
<body class="webucator">
  <h1>Using em</h1>
  <h2 style="margin-left: 2em;">Subtitle 1</h2>
  <h3 style="margin-left: 2em;">Subtitle 2</h3>

  <hr>

  <h1>Using rem</h1>
  <h2 style="margin-left: 2rem;">Subtitle 1</h2>
  <h3 style="margin-left: 2rem;">Subtitle 2</h3>
</body>
</html>

Code Explanation

The code above will render the following:Ems vs Rems

Notice that "Subtitle 1" and "Subtitle 2" do not line up in the Using em section, but do line up in the Using rem section. This is because the ems are relative to the font sizes of their respective header elements, while the rems are not.

Percentages

Percentages are most often used to create flexible layouts that change to fit the size of the browser window. When specifying a value such as width or height in percentages, the percentage is relative to the size of the containing element. For font size, percentages work the same as ems. 100% is equal to the inherited font size, so 100% is essentially 1em when specifying font size. It is most common to use percentages to specify values like width and height to create "fluid" boxes that grow and shrink to fit within the browser window.

Other Units

Inches (in), centimeters (cm), millimeters(mm), points (pt), and picas (pc) are all absolute units that are most often used when designing for print.

You might also run into viewport units, which are relative units based on the size of the viewport (browser window). vw and vh specify sizes relative to the user's viewport width and height, respectively.

  1. vw is 1/100th of the viewport's width.
  2. vh is 1/100th of the viewport's height.
  3. vmax specifies size relative to whichever dimension is larger (width or height).
  4. vmin specifies size relative to whichever dimension is smaller (width or height).

Viewport units are used for designing for screen, but they are not as popular or as well supported as other screen units.

If you would like to play with the different CSS units to see how they compare on a screen, open CrashCourse/Demos/units-of-measurement.html (shown below) in your browser.
Units of Measurement

For more detailed information on CSS values and units see https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Values_and_units

Inheritance

By default, all CSS properties are either inherited or non-inherited properties. This difference determines what happens when a property for an element goes unspecified.

If an inherited property for an element goes unspecified, then that element will inherit the value from its parent element. A common inherited property is font-size:

Code Sample:

CrashCourse/Demos/inherited.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="../normalize.css" rel="stylesheet">
<style>
  p {
    font-size: 20px;
  }
</style>
<title>Inherited Properties</title>
</head>
<body class="webucator">
    <p>This is a paragraph element with a 
        <strong>strong element</strong> within it.</p>
</body>
</html>

Code Explanation

The above code will render the following:Inherited Properties

Notice that the strong element has the same font size as the p element, even though font-size was not specified for it.

If a non-inherited property for an element goes unspecified, then that element will get the initial (default) value of that property. A common non-inherited property is border:

Code Sample:

CrashCourse/Demos/non-inherited.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="../normalize.css" rel="stylesheet">
<style>
  p {
    border: 0.2rem solid black; 
  }
</style>
<title>Non-Inherited Properties</title>
</head>
<body class="webucator">
    <p>This is a paragraph element with a 
      <strong>strong element</strong> within it.</p>
</body>
</html>

Code Explanation

The above code will render the following:Non-Inherited Properties

Notice that the strong element does not also have a border. This is because the initial value for border is none.

The inherit Value

You can force a property to inherit the value of its parent by setting its value to inherit.

The inherit property is most often used to override other rules, as illustrated in the following demo:

Code Sample:

CrashCourse/Demos/inherit-styles.css
h2 {
  color: blue;
}

article h2 {
  color: inherit;
}

#article-red {
  color: red;
}

#article-green {
  color: green;
}

#article-purple {
  color: purple;
}

Code Explanation

Code Sample:

CrashCourse/Demos/inherit.html
---- C O D E   O M I T T E D ----
<body class="webucator">
  <h1>inherit</h1>
  <header>
    <h2>This is the Header</h2>
    <p>This is a paragraph.</p>
  </header>
  <article id="article-red">
    <h2>Article Red</h2>
    <p>This is a paragraph.</p>
  </article>
  <article id="article-green">
    <h2>Article Green</h2>
    <p>This is a paragraph.</p>
  </article>
  <article id="article-purple">
    <h2>Article Purple</h2>
    <p>This is a paragraph.</p>
  </article>
  <footer>
    <h2>This Is the Footer</h2>
    <p>This is a paragraph.</p>
  </footer>
</body>
</html>

Code Explanation

The above code will render the following:inherit Demo

A few things to note:

  1. All h2 elements are given the color blue.
  2. h2 elements within article elements are made to inherit the color property.
  3. Each article is given a different color. This color gets inherited by the h2 elements within them because they have color set to inherit and by the p elements because color is an inherited property.