CSS Part 1

Dr. Greg Bernstein

Updated: August 20, 2019

Getting Started with CSS

Readings

  1. How CSS works

  2. CSS Syntax

  3. Selectors Introduction

  4. Simple Selectors

  5. Combinators

Cascading Style Sheets (CSS)

  • How we specify the styling of an HTML document
  • Style sheet consist of an ordered set of rules

CSS Rules

  • A rule consists of:
    • “A selector, which selects the element(s) you want to apply the updated property values to.” For example we want special styling for the first paragraph in each section of our page.
    • “A set of properties, which have values set to update how the HTML content is displayed”. For example font type, background color, etc…

CSS Example

File FirstCSS.html (our HTML file):

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Our First CSS Example</title>
        <link rel="stylesheet" href="first.css">
    </head>
    <body>
        <h1>A CSS Example</h1>
        <p>Quite ugly styling.</p>
    </body>
</html>

CSS Example

File first.css:

/* CSS comment, No end of line // coments. */
/* Rules for two different elements */
h1 {background-color: skyblue}
p {color: green}

Rendered Page

Browser snapshot:

Rendered Page
Rendered Page

What does the browser do?

From MDN:

The browser converts HTML and CSS into the DOM (Document Object Model). The DOM represents the document in the computer’s memory. It combines the document’s content with its style. The browser displays the contents of the DOM.

Page Rendering

From MDN:

Render Model
Render Model

Applying CSS to HTML

There are three ways to style with CSS from best to worst practice:

  1. External stylesheet (separate file) use <link> tag to reference it.
  2. Internal stylesheet, use a <style>...</style> element in the head
  3. Inline style, use a style attribute on an element.

Example Internal StyleSheet

File SecondCSS.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Our Second CSS Example</title>
    <style>
        /* Inline CSS style sheet, with CSS comment */
        h1 {background-color: skyblue}

        p {color: green}
    </style>
</head>
<body>
    <h1>A CSS Example</h1>
    <p>Quite ugly styling.</p>
    <p>But we aren't worried about that yet.</p>
</body>
</html>

Example Inline Styles

File ThirdCSS.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Our Third CSS Example</title>
</head>
<body>
    <h1 style="background-color: skyblue">A CSS Example</h1>
    <p style="color: green">Quite ugly styling.</p>
    <p style="color: blue">Don't use inline styles
        if you can help it. &#x1F629;</p>
</body>
</html>

Inline style rendering

Renders as:

Third CSS example
Third CSS example

Loading External Stylesheets

  • After the browser gets the HTML page it will make requests for external style sheet, script, image and other files.
  • But not always!!!
  • To save time a browser will cache many of these items and not ask for them again
  • Even when you reload the page!!!

A Problem for Developers

  • If we are developing an external stylesheet we want to make sure it is reloaded
  • Browsers have different behaviors
  • In development mode Chrome allows control when right clicking the reload button.
  • Firefox has an Advanced Setting to disable the HTTP cache when the developer toolbox is open.

CSS Syntax

The CSS Language

From MDN:

CSS is a declarative language, which makes its syntax fairly easy and straight forward to understand. In addition, it also has a very nice error recovery system that allows you to make mistakes without breaking everything — for example declarations that aren’t understood are generally just ignored.

CSS Declarations

From MDN:

CSS Declaration – Property with a value
CSS Declaration – Property with a value

Important: If a property is unknown or if a value is not valid for a given property, the declaration is wholly ignored by the browser’s CSS engine.

CSS Properties

From MDN:

There are more than 300 different properties in CSS and nearly an infinite number of different values. Not all pairs of properties and values are allowed; each property has a specific list of valid values defined for it.

You can look these up at MDN CSS reference.

CSS Declaration Blocks

From MDN:

Grouping declarations together into a block
Grouping declarations together into a block

CSS Selectors and Rules

From MDN:

CSS rule = selectors and declaration block
CSS rule = selectors and declaration block

CSS Rules

From MDN:

Selectors can get very complicated — you can make a rule match multiple elements by including multiple selectors separated by commas (a group,) and selectors can be chained together, for example I want to select any element with a class of “blah”, but only if it is inside an

element, and only while it is being hovered by the mouse pointer.

Other CSS Statements

From MDN:

  • @charset and @import (metadata)
  • @media or @document (conditional information, also called nested statements, see below.)
  • @font-face (descriptive information)

CSS Shorthand

Some properties like font, background, padding, border, and margin are called shorthand properties — this is because they allow you to set several property values in a single line…

  • I generally don’t use these since I don’t tend to remember how they work
  • Except for border when I want to draw a border around an element for debugging purpose.

CSS Selectors Overview

Selector Types

From MDN:

  • Simple selectors: Match one or more elements based on element type, class, or id.
  • Attribute selectors: Match one or more elements based on their attributes/attribute values.
  • Pseudo-classes: Match one or more elements that exist in a certain state, such as an element that is being hovered over by the mouse pointer, …

More Selector Types

From MDN:

  • Pseudo-elements: Match one or more parts of content that are in a certain position in relation to an element, for example the first word of each paragraph, or generated content appearing just before an element.

  • Combinators: … ways of combining two or more selectors in useful ways for very specific selections. So for example, you could select only paragraphs that are direct descendants of divs, …

Yet More Selector Types

  • Multiple selectors: … you can put multiple selectors on the same CSS rule, separated by commas, to apply a single set of declarations to all the elements selected by those selectors.

Simple Selectors

Type Selectors

  • Consists of the elements tag name without < or >
  • For example <ol> becomes just ol Example:
h1 {font-family: sans-serif;
    color: darkblue}
p {background-color: bisque}
strong {background-color: coral}
em {background-color: aqua}

Rendering

Simple Typle Selector Example
Simple Typle Selector Example

Class Selectors

  • The class selector consists of a dot, ‘.’, followed by a class name
  • A class name is any value without spaces put within an HTML class attribute

Class Selectors (HTML)

<ul>
    <li class="first done">Create an HTML document</li>
    <li class="second done">Create a CSS style sheet</li>
    <li class="third">Link them all together</li>
</ul>

Class Selectors (CSS)

.first {
  font-weight: bold;
}

/* All the elements with the class "done" are strike through */
.done {
  text-decoration: line-through;
}

Class Selectors (Rendered)

Class Selectors Rendering
Class Selectors Rendering

ID Selectors

  • The ID selector consists of a hash/pound symbol (#), followed by the ID name of a given element.

  • Any element can have a unique ID name set with the id attribute.

  • It is up to you what name you choose for the ID.

ID Selector Example

<p id="polite">"Good morning everyone."</p>
<p id="rude">"Don't bug me until I've had my tea!"</p>

ID Selector Example

#polite {
  font-family: cursive;
}

#rude {
  font-family: monospace;
  text-transform: uppercase;
}

ID Selector Example

ID Selector Rendered
ID Selector Rendered

Psuedo Stuff

Psuedo-Classes

From MDN: “A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s).”

  • Link related: :active, :visited
  • General: :hover, :nth-child()
  • And others…

Hover Examples

A special paragraph:

This is a special Paragraph.

A secret Message

Code the Web!

HTML for Hover Example

<p id="MySpecialP">This is a special Paragraph.</p>
<div id="HovTarg"><p>A secret Message</p>
<p class="secret">Code the Web!<p>
<div>

CSS for Hover Example

We have not learned about these properties yet!

#MySpecialP:hover
{background-color: blue; color: white}

.secret {display: none}
#HovTarg {position: relative}
#HovTarg:hover p.secret {
  position: absolute;
  padding: 1em;
  top: -2em; left: 0em;
  height: 2em;  width: 10em;
  border: solid black;
  background-color: yellow;
  display: block;
}

Psuedo-Elements

From MDN: “A CSS pseudo-element is a keyword added to a selector that lets you style a specific part of the selected element(s).”

  • Content insertion: ::before, ::after
  • Text related: ::first-letter, ::first-line

first-letter Example

A long time ago in a …

Beam me up Scotty…

First Letter Example

HTML:

<p class="flEx">A long time ago in a ...</p>
<p class="flEx">Beam me up Scotty...</p>

First Letter Example

CSS:

<style>
.flEx::first-letter
{
  font-size: larger;
  color:blue;
}
</style>

Combinators

Decendent and Siblings

  • Decendent selector use a space between any two selectors
  • Child (immediate) selector use a > between two selectors
  • Adjacent Sibling selector use a + between two selectors
  • General Sibling selector use a ~ between two selectors

Example HTML

From MDN

<section>
  <h2>Heading 1</h2>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <div>
    <h2>Heading 2</h2>
    <p>Paragraph 3</p>
    <p>Paragraph 4</p>
  </div>
</section>

Example CSS

From MDN

section p { /* descendent */
  color: blue;
}

section > p { /* child */
  background-color: yellow;
}

h2 + p { /* direct sibling */
  text-transform: uppercase;
}

h2 ~ p { /* any sibling */
  border: 1px dashed black;
}

Rendering

See Combinator1.html1 file.

Testing Selectors from the Console

We can test a fair amount of selectors/combinators from the JavaScript console via the DOM

  • Example: document.querySelectorAll("p") will select and return an array of all the paragraph elements in the document.

  • In general use document.querySelectorAll(YOUR_SELECTOR). Very useful for debugging CSS!

More Combinators

  • AB Any element matching both A and B at the same time.

  • Example:

section.answer {
    border-style: solid;
    border-width: 2px;
    border-color: darkmagenta;
}

Example HTML

<li>Short Problem Description <span class="points">point value</span>
    <p>What can we put within a <em>list item</em> element?</p>
    <section class="answer">
        <p>Students answer here. If short answer just put in a sincle paragraph element.
        If longer answer put in a section element. In either case students should add
        a <em>answer</em> class attribute to the element used.</p>
    </section>
</li>

<li>Another Short Problem Description <span class="points">point value</span>
    <p>General problem instructions and such... A bunch of sub-questions follows.</p>
    <ol type="a">
        <li>Another sub-question
        </li>
        <li>A third sub-question
            <p class="answer">Here is the answer. Note that it is in its
            own paragraph element within the list item element.</p>
        </li>
    </ol>
</li>

Rendering

Matching element and class
Matching element and class

Multiple Selectors

  • You can have multiple selectors apply the same rule.
  • Just separate the selectors by a comma “,”
  • Example
h1, h2, h3, h4, h5, h6 {
  font-family: helvetica, 'sans serif';
}