{the jump}

Intro to CSS

Intro

What is CSS?

  • CSS is a language
  • CSS controls Presentation
    • i.e. how things 'look' on a page
      • colours
      • spacing
      • font
      • background
      • animation (~mostly)
         
  • Side Note: Your HTML content should be usable without CSS

Web Content 3-Layer Model

Progressive Enhancement

Graceful Degradation

Before we start...

  • So, when you first put text into the HTML file, it all ran together.
  • Then you wrapped it in tags and now it's laid out nicer
  • The browser expects you to tell it how to lay things out
    • But, in case those instructions don't turn up, it writes its own so that the page is readable (demo)
    • These are the 'user-agent stylesheets' you just saw in the dev tools
    • Originally, it was intended that it would be like that and that browser makers would determine how your page was displayed, but people INSISTED that they be given a way to control things
    • The browser makers gave them a new language called CSS

Dealing with the default styles

  • Because different browsers have different 'user agent stylesheets' the appearance of our page would be different between browsers if we didn't mitigate this
  • There are 2 strategies we came up with:
  • One is to reset the properties back to 0 with our own css
    • but that requires us to then add a load back in later
  • the other is to normalise our css
    • so using css to achieve a baseline standard
  • Stylesheets for both can be found here:
  • You should put these first before other stylesheets (See 'overriding by order' later on...)
    • Third-party libraries, like Bootstrap, may already include one

Our CSS

Including it

Including CSS in your page...

  • CSS should go in the head of the document (so that it is loaded before the page is rendered).
  • It is loaded using either a style tag, or (preferably) a link to a stylesheet.
    • style block can be used to deliver mission-critical styles (above the page fold)
    • In general, prefer linking a stylesheet
<!DOCTYPE html>
<html>
<head>
    <title>My Page</title>
    <!-- RESET GOES HERE -->
    <!-- THIRD-PARTY STYLESHEETS GO HERE -->
    <style>
        /* CSS GOES HERE */
    </style>
</head>
<body>
...
<!DOCTYPE html>
<html>
<head>
    <title>My Page</title>
    <!-- RESET GOES HERE -->
    <!-- THIRD-PARTY STYLESHEETS GO HERE -->
    <!-- Now your styles -->
    <link rel="stylesheet" href="/styles/styles.css">
</head>
<body>
...

A Note On File Paths (in HTML & CSS files)

  • Paths can be relative or absolute. (we use relative so that the projects are portable.)
  • styles/styles.css - The directory (folder) you're in, into the styles directory to find styles.css (use on the file API, file:///)
  • /styles/styles.css - root of the project (or public dir, when hosted), into styles directory to find styles.css. (Use when served)
  • ./styles/styles.css - Same as the first one, but will not suffer errors if folders are mapped or symlink-ed. (Use if site uses build script)
  • . = 'here' (PWD - 'Present Working Directory')
  • .. = 'up into the parent directory'
  • / = delimiter. They show where a file/directory name starts and ends.
  • Don't put spaces in and try and stay lower case.

More than one stylesheet?

  • You'll be pleased to know, that rather than writing everything yourself from scratch, you can include other people's libraries for CSS & JavaScript
  • The reason you put your stylesheet last is that you can include these and then override them by pasting the same rule into yours and just listing the properties you want changing, with their new values
  • DON'T download and edit 3rd party stylesheets directly
    • or indeed any 3rd party resource
    • copy the rule you want to override into your sheet and modify it as required

Writing it

CSS has mixed case sensitivity

All CSS style sheets are case-insensitive, except for parts that are not under the control of CSS. For example, the case-sensitivity of values of the HTML attributes, including "id" and "class", of font names, and of URIs lies outside the scope of this specification. Note in particular that element names are not case-insensitive in HTML, but case-sensitive in XML.

Comments in CSS

/* This is a comment */

/*************************
*  SO IS THIS
**************************/

/* Comments can be used to organise */

/* Main Nav */
nav { 
  font-weight: bold;
}


/* Product grid */
.product { 
  border: 1px solid #000;
}

`cmd + /` (or `ctrl + /` on windows) to toggle

How do I operate CSS?

  • With CSS you:
    1. Create a 'selector chain'
      • This text tells CSS which elements your rule applies to
    2. then you create a block after it (with braces {})
    3. into which you put a list of declarations, which comprise of
    4. properties
      • like color, or font-size
      • followed by a colon
    5. and values for them
      • like red, or 20px
      • followed by a semicolon
    6. This whole structure is called a Ruleset (or rule for short), which then applies to the elements you just selected

Nomenclature

CSS Rule Example

h1 {
 color: red;
}
<!-- html fragment: for exercise only -->
<h1>My Red Heading</h1>

N.B. You can put more than one declaration in a block.

Selector Chains

Can include:

  • [pseudo] elements - matches the tag name
    • You can inject elements before and after a node using 'pseudo elements' ::before, ::after, which you can then style
  • [pseudo] classes - matches any element with a given class name
    • Classes are so you can say 'this type of thing'
    • Pseudo classes are when something happens to be a type of thing, like a 'hovered thing' or 'the 3rd child element of ...'
  • ​attributes - matches any element with a certain attribute/value to that attribute
  • IDs: DO NOT USE IN CSS! (because no portability - 1 x id per page is valid, and difficult to override) (demo)

Selection Patterns

Simple

Universal Selector

  • * character
  • slow (if used in concert with others, so use sparingly)
  • good for setting box-model to border-box (see later in course)
html {
    box-sizing: border-box;
}

*,
*::before,
*::after {
    box-sizing: inherit;
}

Root Element Selector

  • :root (docs)
  • In HTML, root is the <html> tag
    • It has a higher specificity (see later)
  • It can be other things in other types of document (such as SVG)
  • (Don't worry about it too much for now...)
:root {
  --base-color: white;
}

Side Note: Emmet

  • Whatever short code you used to create an element in your HTML will also select it in your CSS
    • So typing .special and hitting tab will create <div class="special"></div> (div is the default element)
      • .special in the css will select it
    • If you type a[href="#"]#mail-link - you get <a href="#" id="mail-link"></a>
      • [if you were abysmal at CSS] a[href="#"]#mail-link would also select it
    • docs

Element (or Type) Selector

  • Just type the name of the tag
  • It will affect ALL tags on that page that match
    • So use it to create generic rules, e.g. the default size of text
  • So to affect all the paragraphs:
p {
  margin-bottom: 1em;
}

Class Selector

  • Uses the full-stop character (.)
  • To affect an element with a class of <something>
    • This is the main type of selection you're going to use
    • You're saying that something is a 'type of thing', so it should be treated a certain-way
    • This is intentional direct targeting, where element selection is generic.
.section-title {
// ...
}

Presentational CSS

  • Class selectors are the selector type that you will use the most. You create them with a purpose in mind
  • BUT you will have to pick names for your classes
  • Sometimes you are hand-coding, sometimes you are making stuff for a CMS
  • When hand-coding classes picking names like 'red' and 'right' is not advisable
    • We call those 'presentational CSS' and the problem is that over time [some of] the 'red' thing[s] will end up getting change to another colour and becomes confusing
    • Keep to functional names, like 'advertising-section' or 'highlighted'
  • With CMS/Third party libs, presentational classnames are OK because no-one is directly constructing the HTML

ID Selector

  • # character
  • To affect an element with a id of 'special'
  • (ID's are hard to override and non-portable, so don't)
#special {
...
}

matches

<div id="special">.....</div>

Attribute Selector

  • Uses [] characters
  • Full guide here (Demo)
  • You can do multiple selections
  • Use the double quotes for x-browser consistency
a[href^="mailto"] {
...
}

img[alt~="person"][src*="lorem"] { 
  ...
}

Adjacent Selectors

  • Selects element via multiple class/id/attribute combinations
  • To affect an element with a class of 'logo' AND a class of 'intro'
    • Note you only select the classes you need, you don't need all!
.intro.logo {

matches

<? class="logo intro other">.......</?>
[src^="https"].profile {

matches

<? src="https://...." class="profile">....</?>

Note: Over-qualification

/* <p class="intro"> or <p class="intro hello">*/

p.intro {
    color: green;
}

Useful in some circumstances, but usually bad practice:

  • What if you ended up with a blockquote instead of a paragraph?
  • also, it adds to the specificity (see later)

Pseudo Selectors

Pseudo-classes

a:hover {
    ...
}

input:focus {
    ...
}

tr:nth-child(3n+1) {
    ...
}
  • affects elements when they are in a certain state
  • represented with :
  • Example:

More here

States Panel

nth element system

  • First: Numbers in CSS
    • We can use these in calculations (with calc(), for example)
  • Some selectors, like :nth-child() need a formula for which children to select
  • :nth-child(5) - selects the 5th element
  • You can pass them things like 'odd' and 'even'
  • But behind the scenes all this works with a numbering system which uses a multiplier
    • Format: xn [+ or - y], e.g. 2n + 5, 5n, 3n -2 (e.g. :nth-child(5n+1))
  • The way to use these is to run each number (starting at zero) through the equation
    • So 3n + 5 affects the (3*0 + 5), (3*1 + 5), (3*2 + 5) becomes 5, 8, 11, etc. (so every 3rd element, starting at 5)
  • DEMO

:not(<selector>)

p:not(.special) {
  ...
}
  • Filters a selection

^^ That's ALL the paragraphs, but NOT the ones with a class of special

 

  • The selector(s) given to the :not(<this bit>) affects specificity (see later)

Pseudo-elements

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

label::after {
    content: '*';
    color: red;
}
  • affects elements which are not directly in the DOM tree, like 'selected text', injected elements, 'nth-child', etc. (demo)
  • uses 2 colons  (::) (Single colon was CSS2. Avoid.)
  • Needs 'content' to be visible (demo) (show where in elems. panel)

More here

Combinators

Using combinations of selectors

(Selector chains should be ~3 selectors max in length!)

Descendant Combinator

  • a series of selectors, such as ul li
  • This is the main combinator used in CSS
  • CSS is read 'right-to-left'. So 'ul li' is any li with a ul ancestor (not necessarily immediate parent!)
  • GREEDY - Any matching ancestor pattern. (e.g. ul li vs ul li li)
    • CSS is read left to right, so 'any li in a ul'
  • Is not direct descendancy, so the li does not have to be immediately inside the ul (it could be a grandchild)
ul li {
 border: 1px solid;
}

Child Combinator

  • Uses the > character
  • Uses the same pattern as descendant combinator BUT
  • it does require direct descendancy to work
  • So to affect a ul that is an immediate child of an element with a class of product:
.product > ul {
...
}

Adjacent Combinator

  • Uses the + character
  • Uses the same pattern as descendant combinator BUT
  • So to affect a label that is the adjacent sibling of a valid input
input:valid + label  {
    color: green;
}
  • Must be the next element though!!

General Sibling Combinator

  • Uses the ~ character
  • Selects more than one sibling
  • So to affect ALL labels after the input
input:valid ~ label  {
    color: green;
}
  • Must be one of the following sibling elements!!

Applying rules to multiple selections

Stacked selectors:

/* All the <a>s and the <span>s */

a, 
span {
    color: green;
}
  • uses a comma to separate the selector chains

Applying the same style to multiple things

New pseudo selectors:

:is(section, article, aside, nav) :is(h1, h2, h3, h4, h5, h6) {
  color: #BADA55;
}

/* ... which would be the equivalent of: */
section h1, section h2, section h3, section h4, section h5, section h6, 
article h1, article h2, article h3, article h4, article h5, article h6, 
aside h1, aside h2, aside h3, aside h4, aside h5, aside h6, 
nav h1, nav h2, nav h3, nav h4, nav h5, nav h6 {
  color: #BADA55;
}

Another way to apply the same style to multiple things

Override

Overriding

  • CSS rules can override each other
    • There is an algorithm that runs all the rules together and decides what applies - it is called the cascade
  • They do this on a 'granular' basis
    • Only matching parts of the rule are overridden, not all of it.
  • 'What overrides what' is determined:
    • by order
      • so rules that come later in a stylesheet, or come in a stylesheet which is included later will win by this method
    • by the specificity of the selector
      • specificity
    • demo

By Order

stylesheet1.css

stylesheet2.css

h1 {
    color: red;
    text-decoration: underline;
}
h1 {
    color: blue;
}

The declaration from stylesheet2.css will win on color, and the underline from stylesheet1.css will still count

within the same or different stylesheets:

Seeing an override

By Specificity

stylesheet1.css

stylesheet2.css

header h1 {
    color: red;
}
h1 {
    color: blue;
}

Now the heading will be red, even though blue came afterwards, because the selector is more specific

within the same or different stylesheets:

Credit: Chris Coyier @css-tricks.com (https://css-tricks.com/specifics-on-css-specificity/)

Credit: Chris Coyier @css-tricks.com (https://css-tricks.com/specifics-on-css-specificity/)

Credit: Chris Coyier @css-tricks.com (https://css-tricks.com/specifics-on-css-specificity/)

Credit:

Estelle Weyl (http://www.standardista.com)

{the jump} Full-Stack Bootcamp: Session 5

By James Sherry

{the jump} Full-Stack Bootcamp: Session 5

Intro to CSS

  • 1,857