CSE 154

Lecture 3: Introduction to CSS

Today's Agenda

Administrivia

Introduction to CSS

Some basic font and color styles along the way

Week 1 Objectives

By the end of this week, you should be able to:

  • Know how to use important HTML5 elements to structure webpage content
  • Know how to link CSS to separate content from presentation
  • Use basic CSS styles (fonts, colors, etc.)
  • Set font properties in CSS and be able to import Google Fonts
  • Use your Chrome Inspector tool to explore and test CSS properties
  • Know how to select different elements in CSS using selectors, ids, and classes
  • Validate your HTML and CSS pages

Lecture Pre-Checks

First one out now!

You have unlimited attempts to submit before the deadline on lectures.

Use the feedback if you don't get full credit, and review the readings/ask on Piazza if you have any questions!

Creative Project 1

cp turnin example Creative Project is due Wednesday. Remember to add, commit, push again AND submit by clicking the Turn-in button on this page.

Consider opting in for the CP1 Showcase (checkbox during GitGrade submission process) and update showcase-options.txt with the files you want to include/exclude.

Don't forget about the Late Day Challenge!

Due Dates and Lock Dates

Click Turn-in by Due Date?:

  • No late days spent.

Click Turn-in between Due Date and Lock Date?:

  • 1 late day spent per day (24hours) after Due Date

Click Turn-in after Lock Date?:

  • Cannot Turn In. 😞

A Note About Naming in Windows

Please make sure any file names you reference (e.g. html, css, images) in your HTML are all-lowercase (and have no spaces). Windows will ignore casing, but they will appear as broken links on other systems!

Example, if you have an image under "img/pupper.jpg" relative to your HTML file, the first image will render but the second will appear broken on non-Windows systems:

<img src="img/pupper.jpg" alt="my pupper!" />
<img src="img/pupper.JPG" alt="my pupper!" />

HTML

Divs and Spans

"Division" elements that act as containers solely for styling purposes

Generic containers, do not come with any semantic meaning

  • divs are block elements
  • spans are inline elements

Review: What's the difference between block and inline?

Headers and Footers

May also be used in other semantic tags but must relate to the parent content

<section>
  <header>...</header>
</section>

HTML

section elements should almost always have a header, but a h1-h6 heading is also sufficient.

<blockquote>
  <p>
    The Web does not just connect machines, it connects people.
  </p>
  <footer>Tim Berners-Lee</footer>
<blockquote>

HTML

Using a nav Bar

nav is often used for a list of navigational links on web pages

example page with nav bar

Using a nav Bar

What's wrong with the following choice of p tags?

<nav>
  <p><a href="#">Home</a></p>
  <p><a href="koala.html">Koala-tee Facts</a></p>
</nav>

HTML

Some students try to use h1 or p for nav element links. Remember that HTML elements should be chosen based on the meaning of their content, not on the appearance!

Review: Is the link above an example of a relative or an absolute link?

A Better nav Solution

<nav>
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="koala.html">Koala-tee Facts</a></li>
  </ul>
</nav>

HTML

output

But what if you don't want the bullet list appearance?

That's where CSS comes in!

nav li {
  display: inline;
  list-style-type: none;
}

CSS

CSS: Adding Style to our Webpages

Koala page output without CSS Koala page output

Cascading Style Sheets (CSS): <link>

<head>
  <meta charset="utf-8" />
  <link href="koala-styles.css" rel="stylesheet" />
  <title/>Koala Fan Page</title>
</head>

HTML (example)

CSS is used to select elements and define styles to change the appearance and layout of information on a web page

Every web browser has its own defaults for different elements (most give headings bold weight, bullets to lists, etc.)

CSSZenGarden

A project using different CSS templates to style the same HTML page.

CSS Zen Garden Screenshot

Template 116: Ragged

CSS Zen Garden Screenshot

Template 143: Verde Moderna

CSS Zen Garden Screenshot

Template 214: Pixelisation

CSS Zen Garden Screenshot

Template 219: Steel

CSS (and JavaScript) in Action.

CSE154 April Fools Theme.

Review: Terminology

A CSS rule is a selector followed by a set of declarations, each a property/value pair.
Image source: MDN

Selectors designate exactly which element(s) to apply styles to

Properties determine the styles that will be applied to the selected element(s) (background-color, font-size, etc.)

Each property has a set of values that can be chosen (e.g. 14pt value for font-size property)

There are currently over 200 possible style properties to choose from - use the Chrome inspector for useful autocomplete of property values!

CSS Properties for Colors

p {
  color: red;
  background-color: yellow;
}

CSS

This paragraph uses the style above.

output

Property Description
color color of an element's text
background-color background color that will appear behind the element

A great MDN reference page for different color values here!

Chrome Inspector: Color Picker

chrome color picker

The Chrome inspector gives you a useful feature to look at different color code representations (e.g. HEX, RGB) as well as opacity settings, eyedropper, etc.)

When you are looking to choose colors for you page, this can be useful to see the effects real-time (then copy/paste the code to set the color in your CSS).

Chrome Inspector: Eyedropper Feature

chrome eyedropper

Fonts: font-family

h4 {
  font-family: "Courier New", monospace;
}

p {
  font-family: Georgia, serif;
}

CSS

This h4 uses the first style above

This paragraph uses the second style above

output

Enclose multi-word font names in quotes!

More about font-family

p {
  font-family: Garamond, "Times New Roman", serif;
}

CSS

This paragraph uses the above style

output

Can specifiy multiple fonts from highest to lowest priority

Generic font names:

  • serif, sans-serif, cursive, fantasy, monospace

If the first font is not found on the user's computer, the next is tried

Generally should specify similar fonts

Placing a generic font name at the end of your font-family value ensures that every computer will use a valid font

Using Google Fonts

  1. Go to https://fonts.google.com
  2. Find the font(s) you like. Press the + button for each
  3. Click on the black bar that says the number of families you have selected
  4. Click on @import and copy the text between the <style> and </style> tags
  5. Paste the code into your .css document (see example here)

Demo

Using Google Fonts (Step 1: Find a Font(s) and Customize any Options)

Google Font screen

Using Google Fonts (Step 2: @import in your External CSS)

Google Font screen

Copy/paste the text inside of the style tags - you should put this at the top of your external CSS stylesheet

Then use the rules shown, which include the default font specified for your chosen font(s).

Paste the code into your .css document (see example here)

Three Ways to Add CSS to Web Pages

  • External stylesheets (the preferred way)
  • Internal stylesheets
  • Inline styles

External Stylesheets

<head>
...
  <link href=styles.css" rel="stylesheet" />
...
</head>

index.html

body {
  background-color: #AED581;
}

styles.css

The link tag is used to define the relationship between HTML and CSS

Use the rel attribute with a value "stylesheet" to specify this relationship

Use the href attribute to identify a path to the CSS file

Sharing CSS Between Multiple HTML Files

<head>
  ...
  <link href="styles.css" rel="stylesheet" />
  ...
</head>
... rest of HTML
        

index.html

<head>
  ...
  <link href="styles.css" rel="stylesheet" />
  <link href="koala-styles-custom.css" rel="stylesheet" />
  ...
</head>
... rest of HTML

koala.html

body {
  background-color: #AED581;
} 

styles.css

Multiple HTML files can share the same CSS, and one HTML file can have multiple CSS files (loaded in order)

Q: What do you think would happen if you have a body style for both styles.css and koala-styles-custom.css?

The "Cascade" of CSS

All styles "cascade" from the top of the sheet to the bottom

  • When you add a second file, these are overwritten
  • Take care not to override styles if possible
  • If you have styles specific to a page, use a second sheet (usually linked after the shared one)

Internal Style Sheets

Another way to include style in your web page, a style sheet in your <head>

DO NOT DO THIS, but you may see this in code you find online. Why is this poor code quality (think about a more complex website)?

<head>
  <link rel="stylesheet" href="precedence.css">
  <style>
    <!-- internal style sheet, the linked style has color: purple rule -->
    p { color: green; }
  </style>
</head>
<body>
  <p>This is another paragraph</p>
</body>

HTML

This is a paragraph

output

Internal style takes precedence whether it is before or after the linked style in the head

Inline styles: the style attribute (BAD)

This is also bad code quality; DO NOT DO THIS

<p style="font-family: sans-serif; color: red">
  This is a paragraph
</p>

HTML

You will unfortunately see this on some sites like W3Schools

It does render as you would expect though...

This is a paragraph

output

Online Resources: Good or Bad?

You may find some resources online helpful to explore different ways to use CSS properties - there are a ton of things! But some are better than others (make sure you understand why these examples are poor use of HTML and CSS).

Understanding good code quality can be extremely valuable in navigating an overwhelming amount of resources on the web today.

A good discussion.

Understanding the Good vs. Bad

We choose resources that best align with our code quality guidelines, while giving just enough "extra detail" into topics we cover in lecture/section/lab. That said, let us know if you're looking for recommendations on a specific resource!

Remember that all of your work must be your own, and cite any tutorials/resources you may be using to explore features you may be exploring.

CSS Selectors

Used to select specific HTML elements in CSS

CSS Selectors: Simple selectors

Classifcation Description Example
Type Selector Selects an element type p
Class Selector Selects all elements with the given class attribute value .koala-face
ID Selector Selects the with the unique id attribute value #scientific-name

NOTE: * selector by itself is bad style (except when used in combination).

Type Selector

body {
  background-color: #AED581;
}

CSS

Selects an HTML element

To apply a style to the entire body of your page, write a selector for the body (saves you from manually applying a style to each element)

id and class

id
Unique identifier for an element
Each unique id can only appear once per page
Each element can only have one id
class
Non-unique grouping attribute to share with many elements
Many elements (even of different types) can share the same class
Each element can have many different classes

Example

See the Pen Class and ID example by Melissa Hovik (@krimsonkoi) on CodePen.

Both paragraphs have the same class (product), but each has its own ID

Example using Classes in the Koala Page

<h2>
  <span class="koala-face">(*'0'*)</span> Koala Facts! <span class="koala-face">(*'0'*)</span>
</h2>

HTML

.koala-face {
  font-family: "Roboto Mono", monospace;
}

koala-styles-custom.css

(*'0'*) Koala Facts! (*'0'*)

output

This is a good use of classes because the styles are shared by both spans

This is a good use of a span because it is used only for styling an inline region of content

Example using ID in the Koala Page

<figcaption id="scientific-name">Phascolarctos cinereus</figcaption>

HTML

figcaption {
  font-weight: bold;
  text-align: right;
}

#scientific-name {
  font-style: italic;
}

koala-styles-custom.css

figure caption example with classes figure caption example with classes

This is a good use of an ID because we don't want to italicize both figcaptions

Beyond here was not covered in Lecture.

Grouping Styles

section {
  background-color: #222222; /* dark gray background */
}

header, article, aside, footer, p {
  background-color: #E8E8E8; /* light gray background */
}

CSS

A ruleset can select multiple elements separated by commas

The individual elements can also have their own styles (like section above)

Combinator (Hierarchy) Selectors

Combinators use the HTML document (DOM) hiearchy to select elements

Classification Description Example
Descendent Combinator: A B Selects all B descendents somewhere inside A elements ul li
Child Combinator: A > B Selects all B descendents directly inside A elements ul > li

Combinator Selector Examples

<p>Shop at <strong>Hardwick's Hardware</strong>...</p>
<ul>
  <li>The <strong>best</strong> prices in town!</li>
  <li><em><strong>Act</strong></em> while supplies last!</li>
</ul>

HTML

How would we apply uppercase styling to all strong elements that are...

  • Descendents of li elements?
  • Direct children of li elements?

Descendent Combinator: A B

See the Pen Descendent Combinator by Melissa Hovik (@mehovik) on CodePen.

Child Combinator: A > B

See the Pen Child Combinator by Melissa Hovik (@mehovik) on CodePen.

Combinators in Our Koala Page

This page has a header at the top of the page, and in the Koala Facts section. How could we italicize only the "A Koala-tee Webpage" header directly in the body, without adding an id?

<body>
  <header>
    <h1>A Koala-tee Webpage</h1>
  </header>
  <main>
    <aside> <!-- Left sidebar --> </aside>

    <section>
      <header>
        <h2>*('0')* Koala Facts! *('0')*</h2>
      </header>

      <!-- Koala fact paragraphs -->

      <article>
        <!-- Koala art gallery -->
      </article>
    </section>
  </main>
  <footer><!-- Image citations --></footer>
</body>

HTML

body > header {
  font-style: italic;
}

CSS

Sample Koala Page

When should you use id or class?

Prefer type selectors over classes and ids when you can - we often style our page elements based on their purpose in the document (e.g. all sections might share the same background)

If you have multiple different elements that share styles, then you might consider using a class.

Only use an id for unique elements that are not already uniquely identified by an element (body should not have an id since it is always unique).

Some Useful Selector Practice

Extra Practice from Thursday's section

CSBS selector mystery (from past CSE 154 exam)

http://toolness.github.io/css-selector-game/: a great game to practice selectors

https://flukeout.github.io: another game to select "plate" elements with selectors

Last Reminders for CP1

Use the W3C validators for HTML and CSS (copy/paste option is recommended)

Review the Code Quality Guide for HTML/CSS, and check the spec carefully to make sure you've met all of the requirements

Use Piazza to ask questions

Have fun and be creative!

Remember to add, commit, push and then click the Turn-In button in order to submit your final version