CSE 154

Lecture 4: More CSS - Common Styles and Selectors

Agenda

  • Administrivia
  • CSS
    • Review: Terminology and Syntax
    • id and class attributes
    • Selectors (context, psuedo, etc.)
    • Overview of Useful CSS Properties

Administrivia

HW1 is out

CP1 due tonight tomorrow

Consider opting in for the CP1 Showcase!

Use the extra CP day to try anything you want to practice more before HW1 (e.g. semantic tags and CSS usage)

Lecture Objectives

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

  • Know how to assign colors on webpages using different encodings (hex, rgb, names)
  • Know how to use your Chrome/Firefox inspector tool to test CSS properties
  • Know how to set font properties in CSS and how/why to use defaut fonts when the first font listed is unavailable
  • Know how to import and use a Google font in CSS
  • Understand the differences between classes/ids
  • Know how to select different elements in CSS using ids/class, grouped selectors, and context selectors

"Gots and Needs" Notecards

On one side of the notecard, write what you feel like you've "got" from lecture/section/lab/CPs.

On the other side of the notecard, write 1-2 things you feel you still need to understand, or that would help you understand this material.

Review: Basic CSS Rule Syntax

selector {
  property: value;
  property: value;
  ...
  property: value;
}

CSS (template)

p {
  color: red;
  font-family: sans-serif;
} 

CSS (example)

A CSS file consists of one or more "rule sets"

A rule selector specifies HTML element(s) and applies style properties

Terminology Clarifications

h1, p {
  color: blue;
  background-color: rgb(30, 30, 30);
}

h1 {
  font-style: italic;
}
        
nav ul {
  list-style-type: none;
  color: gray;
}

CSS

How many different rule sets?

How many different rules?

How many different properties?

How many different selectors?

3

5

4

3

Common Text/Color/Background CSS Rules (more here)

CSS Rules Description
color, background-color Foreground (text) color and background color styles
font-family, font-size, font-style, font-weight Various font styles
text-align, text-decoration, text-indent, text-shadow, text-transform Various text styles
line-height, word-spacing, letter-spacing Line/word/letter spacing styles
list-style-type List item styling (e.g. bullet styles)
background-image, background-repeat, background-position, background-attachment, background-size Various background styles

CSS Properties for Foreground and Background 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

More about Colors in CSS

p { color: red }
h2 { color: rgb(128, 0, 196); }
h4 { color: #FF8800; }

CSS

This paragraph uses the first style above

This h2 uses the second style above

This h4 uses the third style above

output

Color names: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, yellow

RGB codes: red, green, and blue values from 0 (none) to 255 (full)

Hex codes: RGB values in base-16 from 00 (0, none) to FF (255, full)

Example: To get red font, you can use either "red", "rgb(255, 0, 0)", or "#FF0000".

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

CSS Properties for Fonts

Property Description
font-family which font will be used
font-size how large the letters will be drawn
font-style used to enable/disable italic style
font-weight used to enable/disable bold style
Complete list of font properties

font-family

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

p {
  font-family: Georgia;
}

CSS

This paragraph uses the first style above

This h4 uses the second style above

output

Enclose multi-world font names in quotes

More about font-family

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

CSS

This paragraph uses the above style

output

Using non-standard fonts with @font-face

Occasionally you want to use a non standard font in your website.

Webfonts is one way you might see some people do it.

@font-face {
  font-family: mySerifWebFont;
  src: url("webfont.ttf");
}

p {
  font-family: mySerifWebFont, serif;
}

CSS

When setting font-family, make sure your listed fonts all share the same classification (serif, sans-serif, monospace, cursive)

BETTER! Use 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)
Google Font screen

font-size

p {
  font-size: 14pt;
}

CSS

This paragraph uses the above style

output

Units:

  • Pixels (px) - e.g., 16px
  • Point (pt) - e.g., 16pt
  • m-size (em) - e.g., 1.16em

Vague font sizes: xx-small, x-small, small, medium, large, x-large, smaller, larger,

Percentage font sizes: 90%, 120%

More about units here.

font-style, font-weight

p {
  font-style: italic;
  font-weight: bold;
}

CSS

This paragraph uses the above style

output

Either of the above can be set to normal to turn them off (e.g., headings)

CSS properties for text

PropertyDescription
text-align alignment of text within its element
text-decoration decorations such as underlining
text-indent indents the first letter of each paragraph
text-shadow a colored shadow near an existing piece of text (CSS3)
text-transform controls capitalization of text
line-height, word-spacing, letter-spacing gaps between the various portions of the text
Complete list of text properties

text-align

blockquote { text-align: justify; }
h2 { text-align: center; }

CSS

The Emperor's Quote

[TO LUKE SKYWALKER] The alliance... will die. As will your friends. Good, I can feel your anger. I am unarmed. Take your weapon. Strike me down with all of your hatred and your journey towards the dark side will be complete.

output

Can be left, right, center, or justify (which widens all full lines of the element so that they occupy its entire width)

text-decoration

p { text-decoration: underline; }

CSS

This paragraph uses the style above

output

Can also be overline, line through, blink or none

Effects can be combined:


p { text-decoration: overline underline; }

CSS

This paragraph uses the style above

output

text-shadow

p {
  font-weight: bold;
  text-shadow: -2px 5px gray;
}

CSS

This paragraph uses the style above

output

shadow is specified as an X-offset, a Y-offset, or an optional color

text-transform


            

I just just CAN'T make up my mind!

HTML

em {
  text-transform: lowercase;
}

span {
  text-transform: capitalize;
}

strong {
  text-transform: uppercase;
}

CSS

I just CAN'T make up my mind!

output

The list-style-type property

ol { list-style-type: lower-roman; }

CSS

Possible values:

  • none: No marker
  • disc (default), circle, square
  • decimal: 1, 2, 3, etc.
  • decimal-leading-zero: 01, 02, 03, etc.
  • lower-roman: i, ii, iii, iv, v, etc.
  • upper-roman: I, II, III, IV, V, etc.
  • lower-alpha: a, b, c, d, e, etc.
  • upper-alpha: A, B, C, D, E, etc.
  • lower-greek: alpha, beta, gamma, etc.
  • others: hebrew, armenian, georgian, cjk-ideographic, hiragana, katakana, hiragena-iroha, katakana-iroha

CSS Properties for Backgrounds

Property Description
background-color color to fill background (previously mentioned)
background-image image to place in background
background-position placement of background image within element
background-repeat how background image should be repeated
background-attachment whether background image scrolls with page
background-size how large the background appears behind the element
background shorthand to set all backgroud properties
More background properties

background-image

body {
  background-image: url("paw.jpg");
}

CSS

This is the first paragraph

This is the second paragraph...
It occupies 2 lines

output

Background image/color fills the element's content area

background-repeat

body {
  background-image: url("paw.jpg");
  background-repeat: repeat-y;
}

CSS

This is the first paragraph

This is the second paragraph...
It occupies 2 lines

output

Can be repeat (default), repeat-x, repeat-y, or no-repeat

background-position

body {
  background-image: url("paw.jpg");
  background-repeat: no-repeat;
  background-position: 370px 20px;
}

CSS

This is the first paragraph

This is the second paragraph...
It occupies 2 lines

output

Value consists of two tokens, each of which can be top, left, right, bottom, center, a percentage, or a length value in px, pt, etc.

Value can be negative to shift left/up by a given amount

Methods for Styling Different Elements in CSS

  • Grouping
  • ids and classes
  • Context selectors
  • psuedo-selectors

Grouping Styles

p, h1, h2 {
  color: green;
}

h2 {
  background-color: yellow;
}

CSS

This paragraph uses the above style.

This h2 uses the above styles

output

A style can select multiple elements separated by commas

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

Body Styles

body {
  font-size: 16pt;
}

CSS

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)

* Selector

* {
  font-size: 14pt;
}

section * {
  border: 2pt solid black;
}

CSS

To select all elements on the page, you can use the * selector.

To select all elements which are children of a parent element, you can use the * selector inside of the parent.

You should in general avoid using this selector though if 1) there is a more specific selector you can use or 2) you end up overriding the styles later.

id and class

id
Unique identifier for an element
Only allowed one id value 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

<p id="product-12345" class="product">Puppy calendar</p>
<p id="product-133337" class="product">Cat mug</p>

HTML

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

Why are these useful?

Gives you another way to talk about your content in CSS (and later in JavaScript)

#my-id {
  /* ... properties ... */
}

.my-class {
  /* ... other properties ... */
}

A mnemonic: .java programs compile into .class files so...
try to remember dot (.) class and hash (#) id

id or class?

How do you decide whether to use an id or a class?

Probably prefer class. You can only use an id once per page, so it's good to be a little stingy with them. classes are free.

On the other hand, if you know you are making a unique section or page element (e.g., submit button), id is the way to go.

A caveat:

It's easy to just make classes for everything, but don't forget that HTML is made to describe your content. So, prefer a <p> tag over a class named paragraph.

CSS Context Selectors

Context selectors are used to selectively style page elements

Examples:

selector1 selector2 {
  properties
}

CSS

... applies the given properties to selector2 only if it is inside a selector1 on the page

selector1 > selector2 {
  properties
}

CSS

... applies the given properties to selector2 only if it is directly inside a selector1 on the page with no tags in between

Check out this neat game for some motivating practice :)

Context Selector Example (without >)

<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

li strong { text-decoration: underline; }

CSS

Produces:

Shop at Hardwick's Hardware...

  • The best prices in town!
  • Act while supplies last!

output

Context Selector Example (with >)

<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

li > strong { text-decoration: underline; }

CSS

Produces:

Shop at Hardwick's Hardware...

  • The best prices in town!
  • Act while supplies last!

output

CSS pseudo-classes

          a:link    { color: #FF0000; } /* unvisited link */
a:visited { color: #00FF00; } /* visited link */
a:hover   { color: #FF00FF; } /* mouse over link */

CSS

ClassDescription
:active an activated or selected element
:focus an element that has the keyboard focus
:hover an element that has the mouse over it
:link a link that has not been visited
:visited a link that has already been visited
:first-letter the first letter of text inside an element
:first-line the first line of text inside an element
:first-child an element that is the first one to appear inside another
:nth-child(N) applies to every Nth child of a given parent

CSS Comments: /* ... */

/* This is a comment.
   It can span many lines in a CSS file. */
p {
  color: red;
  background-color: aqua;
}

CSS

CSS (like HTML) is usually not commented as much as code such as Java

The // single-line comment is NOT supported in CSS

The <-- ... --> HTML comment is also NOT supported in CSS

W3C CSS Validator

<p>
  <a target="_blank" href="http://jigsaw.w3.org/css-validator/">
    <img src="http://jigsaw.w3.org/css-validator/images/vcss"
         alt="Valid CSS!" />
  </a>
</p>

HTML

Valid CSS!

output

Checks your CSS to make sure it meets the official CSS specifications

More picky than the web browser, which may render malformed CSS correctly

Embedding style sheets: <style> (BAD)

<head>
  <style type="text/css">
    p { font-family: sans-serif; color: red; }
    h2 { background-color: yellow; }
  </style>
</head>

HTML

CSS code can be embedded within the head of an HTML file

This is bad style; DO NOT DO THIS (why?)

Inline styles: the style attribute (BAD)

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

HTML

This is a paragraph

output

Higher precedence than embedded or linked styles

Used for one-time overrides and styling a particular element

This is bad style; DO NOT DO THIS (why?)

Content vs. Presentation

HTML is for content; what is on the page (heading; list; code; etc.)

CSS is for presentation; how to display the page (bold; centered; 20px margin, etc.)

Keeping content separate from presentation is a very important web design principle

If the HTML contains no styles, its entire appearance can be changed by swapping .css files (recall CSSZenGarden)