html icon

CSS

Cascading Style Sheets

Image from 20thingsIlearned - Google

What is CSS?

* * *

  • Defines a Web page’s appearance
  • Plain text file with rules for the display of HTML elements
  • CSS associates style rules with HTML elements
  • Separates style and content
  • Formatting includes fonts and colors as well as layout and position
  • Can be created outside of your HTML and applied to multiple Web pages
  • Well-formed HTML is important for your CSS to work properly
graphic of html structure

Before CSS..

  • Pages were styled with some HTML tags and attributes. First webpage
  • <center>, <align>
  • <font>, <text>
  • <background>, <bgcolor> etc
  • the W3C recommended CSS1 in 1996
  • The first commercial browser to support CSS was Microsoft's Internet Explorer 3, released in 1996.
  • Later on, all browsers offered support for CSS
  • CSS2 was released in 1998
  • CSS 3 is the latest standard for CSS
  • CSS is evolving constantly and there are always new features coming up

How do we use CSS?

graphic explaining how css styles are shared between multiple pages.

Where do we add CSS?

🤩

External File

  • Better for maintainig multiple files
  • Keeps structure and presentation separate
  • Add link to the head section of the file
  • <link rel="stylesheet" href="/css/styles.css">

😐

On the Head tag

  • It is always recommended to use external styles
  • Internal styles are good if you have a page with different styles than the rest

😡

Inline

  • Not recommended in most cases.
  • Hard to maintain
  • Acceptable on HTML emails

How does CSS work?

  • Imagine there is an invisible box around every HTML element
  • You assign an id or a class and apply the style on the css file
  • All web pages are made of invisible boxes
css structure

ID's and Clases

These are CSS selectors that allow you to identify the HTML elements for styling and scripting

ID

  • Preceded by the # in the css
  • can only identify one element in the page
  • #blue can only be applied to one html tag
  • <p id="blue">This is the text with an id </p>

Other selectors

  • Type selectors: Applied to any type tag, p, h1,h2, etc
  • General selectors: Applied to any html tag: ul, li
  • div, header, footer, nav etc.

Class

  • Preceded by a . in the css
  • can identify multiple element in the page
  • .black can be applied to many html tags
  • <p class="black">This is a text with an class </p>

As a general rule, it is better to use element selectors first, then classes, and last id's. Using the less specific selectors first, allows for more flexibility later on.

Basic Structure of CSS Rules.

Rules are made of selectors (where the style is applied to) and declarations (the attribute to apply)

css structure multiple selectors
  • Always start and en with a curly bracket { }
  • Use descriptive names for your id's and classes
  • You can use underscore (_), a hyphen (-) or a letter (a-z)/(A-Z) followed by numbers
  • You cannot start a class with a number
  • Use hyphens or underscores to separate words
  • You can apply the same properties to more than one element

CSS Declaration

css declaration declaration blocks
  • Properties indicate the aspects of the element you want to change
  • You can add as many properties as you need in a declaration.

The Box Model

Each box can have padding and margin. The default value is 0 unless it has a pre-set browser style.
(e.g.: paragraphs and headings have default margins.)

The css box model

Each box has the following components

  • Content: The text, image or content inside the box.
  • Padding: The space between the content and the border of the box.
  • Border: The edge of the box
  • Margin: The space between the box and surrounding elements.
  • By default the box will take the dimensions of the content
  • You can specify the dimensions using px, %, or ems.

Margin or Padding?

Difference between Margin and Padding

Depending on the box-sizing settings, the padding will be added to the inside or the outside of the element

box-sizing: content-box (padding expands the size of the element)
box-sizing: border-box (padding does not affect the size of the element)

Block or Inline

In CSS, elements have one of two main display properties by default: block or inline.

The css box model
  • Block: The element will take the full width of the parent container and will start in a new line. (h1, p, div). Block Elements stack on top of each other vertically.
  • You can apply properties like width, height, margin, padding and border, to block-level elements.
  • Inline: The element will only take the space of its content and will not break the flow of content by creating a new line (b, i, span)
  • Properties like width and height will have no effect. Margin and padding will only work horizontally.

Inline-Block

Inline-Block makes block elements behave like inline elements, but with the properties of a block element.

The css box model
  • You can apply properties like width, height, margin, padding and border, to inline-block elements.
  • The element will only take the space of its content and will not break the flow of content by creating a new line.
  • Use inline-block when you want elements to flow horizontally, while keeping block level styling properties.

What about Images?

Images in HTML behave by default as an inline-level elements.

Images are a special case. They are by default inline, but have many properties of a block.

An Atlas Moth An Atlas Moth
Inside a p tag.

An Atlas Moth An Atlas Moth

Inside a div tag.

Element display defaults.

Developer Tools

Every Browser has a tool to inspect the content of a website. It's an important tool for web developers.
The Inspector allows you to inspect and explore the structure of a web page's HTML and CSS. You can select and highlight elements on the page to view their styles, properties, and the box model. It's useful for identifying layout issues and understanding how a page is constructed.

Developer Tools screenshot

The Display Property: Changing Box Behavior

Each box has a default behavior that can be changed with the display property.
By default every element is block or inline.

  • Block: Displays each element in its own line.
  • Inline: Displays the element beside the previous one. Custom height and width will be lost.
  • inline-block: Makes a box element inline, retaining it's block element properties.
  • none: removes the element from view.
  • Flex: used to implement the Flexible Box Layout
  • Grid: used to implement the Grid Box Layout

Block vs. Inline vs. Inline-Block

Each Display property has specific rules for css styling.

Property Inline Inline-block Block
Break Line No No Yes
Padding Left and Right only All four sides All four sides
Margin Left and Right only All four sides All four sides
Width Not Allowed Allowed Allowed
Height Not Allowed Allowed Allowed

Is this supported?

Modern browsers support many aspects of CSS3 but is a good idea to check support at caniuse.com

CSS3 Taxonomy

CSS Color

Specifies the color of the text on the document

HTML Color Codes

Hex Values

  • Hexadecimal is a number system that uses 16 unique symbols to reopresent a value
  • 0-9 and A-F make up those unique symbols.
  • Always preceded by the # sign
  • #000000 = black
  • #FFFFFF = White
  • This is the system most commonly used to assign solid colors.

HTML Color codes.

RGB

  • It's the combination of Red, Green and Blue values
  • It is the standard color system for computer screens and displays
  • The property always states the color system and the values in (). color: rgb(0,0,0);
  • There are 255 possible values for each color
  • rgb (0,0,0) = Black
  • rgb (255,255,255) = White
  • You can also add transparency by adding an alpha value (0 to 1)
  • color: rgba(0,0,0,.5);

HSL

  • It's the combination of Hue, Saturation and Lightness or Luminosity
  • hsl(0, 100%, 50%) HSL
  • The first value represents the hue (0 and 360 are red)
  • The second value represents the saturation (0% is gray, 100% is full color)
  • The third value represents how light or dark the color is (default is 50%).

Named Colors

  • There are 140 pre-defined colors that browsers recognize by name
  • You can use the name or the hex or rgb value.

Backgrounds

Since CSS treats HTML elements as if they were inside an imaginary box, we can add a backround to them.

You can apply the following properties to the background of an HTML element:

  • background-color
  • background-image
  • background-position
  • background-size
  • background-repeat
  • background-attachment
  • background-origin
  • background-clip

Background Color

  • You can apply a background color the same way you apply the font color
  • Use Hex colors, RGB, HSL and named colors.
  • background-color:#ff0000;

Background Images

  • Images can be used as backgrounds
  • Only use them if they are not part of the content and are meant as a decorative background
  • Background images are ignored by web crawlers and screen readers
  • background-image: url(images/my-image.png)

How to use Background images

How to Make Pizza

Demonstration of how to add toppings to pizza

How to add the toppings

Spread the fresh Mozzarella on top of the tomato sauce and other toppings and sprinkle with basil leaves. (See photo)

Fonts

I have a lot of fonts on my computer. Can I use them on my website?

Desktop fonts are different than webfonts. You cannot use the fonts on your computer for websites unless you have a web version uploaded to the server or a web font link.

There are a few fonts that are safe to use for web and that will work in any computer:

  • Web safe serif fonts: Times New Roman, Georgia, Palatino, Lucida Bright.
  • Web safe sans-serif fonts: Arial, Tahoma, Trebuchet MS, Verdana
  • Web safe monospaced fonts: Courier, Courier New, Lucida Sans Typewriter.
  • Web safe specialty fonts: Copperplate, Papyrus, Arial Black, Arial Narrow

Serif Fonts

A serif is a small decorative stroke at the end of a letter or symbol.

  • ABC

San Serif Fonts

San Serif means that the letter does not have the lines attached.

  • ABC

Always choose a font that is easy to read, has good contrast and can be read in different devices. More info about fonts

Font Attributes

Below are the most common properties you can change in web fonts:

  • color: Changes the font color
  • font-family: Specific families go in "", and you can specify fall back options in case the font is not available ("Roboto", Arial, sans-serif)
  • font-size: Use px, %, em or rem, or keywords more on font sizes
  • font-style: normal, italic, oblique
  • font-weight: normal, bold, light, bolder, lighter, numeric value
  • text-align: left, right, center, justify (not recommended for web paragraphs)
  • text-decoration: underline, overline, line-through
  • text-transform: uppercase, lowercase, capitalize

Google Fonts

Google fonts allows you to use different fonts on your website by replacing the default font family with the one you choose.

I'm a Google Font

google fonts embed instructions

Hover Selector (Pseudo class)

The CSS :hover selector is one of many pseudo-classes that are used to style elements

Pseudo-classes are used to define a special state of an element, for example when the user interacts with an element or certain conditions are met.

There are many pseudo classes but the most common is the :hover. It is most often applied to links but it can be applied to any element.

Other common pseudo classes are: :nth-child, :first-child, :last-child, :nth-of-type

Most common uses for :hover are:

  • Change the color and attributes of links
  • Change background
  • Swap images
  • Transform element

.myLink{ color:#000000; }

.myLink:hover{ color:#ff0000; }

CSS: Cascading Style Sheets

What does Cascading mean?

  • The Cascade is the way the browser decided which style applies to an element when style rules are in conflict.
  • It goes from the least specific styles to the more specific ones.
  • We can think of css rules as having weight or a point system to determine which rule wins
  • Specificity Calculator

There are some factors that determine which style rule wins out:

  1. Initial & Inherited Properties (least weight)
  2. Order of Appearance
  3. Selector Specificity
  4. Origin & Importance (Most weight)

Initial & Inherited

  • This is the first stop in the Cascade
  • Initial applies the default values when there are no styles applied to the element.
  • These are the default browser styles
  • It is not really part of the cascade but it still counts as it applies styles to the html.

Tags have parents too!

  • Inherited applies some parent styles to the children
  • Not all properties can be inherited
tag inheritance graphic

Inherited Tags

Some tags inherit the properties of the parent element and others are applied to the selected element only.

Text Properties

  • Font-family
  • Font-size
  • Font-style
  • Line-height
  • color
  • Text-decoration
  • Text-alignment
  • Text-transform

List Properties:

  • List-style-type
  • List-style-image
  • List-style-position

Other inherited tags

  • Visibility
  • Opacity
  • Vertical alignment
  • Quotes
  • Cursor
  • text-shadow

NON-Inherited tags

  • Display
  • Width
  • Height
  • Margin
  • Padding
  • Border
  • Position
  • Background

Source Order: Last Come, First Serverd???

  • Here the browser looks at all CSS selectors used in the file.
  • Think of it as layers. The top layer is the visible one.
  • Looks at the external, local and inline styles
  • When two selectors have the same attributes and specificity, the one that comes last in the code wins.
  • The order in which you link the styles also matters.
  • You can say that the closest to the element to style, the stronger. (inline, in-page, external css)

Selector Specificity

  • This is the third stop in the Cascade
  • Here the browser looks at the selectors used in the CSS declaration
  • According to their specificity the "winning" rule will be applied

The order of priority is as follows:

  • Type and html selectors will be looked first.
    a, p, div, section, h2
  • Classes will override the type and element ones.
    a.myClass{} will override a{}
  • Id's will override classes.
    p#myId{} will override p.myClass, regardless of order
  • Inline styles will override previous ones.
    The closer the style to the element, the stronger.

Origin & Importance

  • This is the last stop in the Cascade
  • Using !important at the end of a declaration overrides everything else
  • Then, Origin looks at where the css rule is originated to see which one wins. (browser, user, website)
  • !important is used as a last resort when all else fails.
  • Understanding the Cascade

CSS Units

  • px

    A pixel is a unit of the display screen.

  • %

    Refers to a percentage in relation to the immediate parent element.

  • em

    An em is a unit based on a font-size. If used in fonts, it's based on the font-size of the parent element. If used in other elements, it's based on the font-size of that element.

  • rem

    A rem is a unit based on the root font-size of your html document. If you did not specify a root font element, the root font will be set by the browser. In most cases is 16px.

  • vh

    Stands for viewport height and it's 1% of the height of your browser window.

  • vw

    Stands for viewport width and it's 1% of the width of your browser window.

Understanding EMS and REMS

explanation of how rem and ems work

Styling Tables

When to use tables? If you would usually add this information in a spreasheet, then it's a table.
If you just want to making things look organized on a page, use CSS.

On the HTML

  • Use colspan to merge columns:
    • <th colspan="2">
  • Use rowspan to merge rows:
    • <th rowspan="2">
  • You can use header, body and footer in tables.
    • <thead>
    • <tbody>
    • <tfoot>
This is the Table Heading heading
Cell 1 Cell 2 Cell 3 Cell 4 Cell 5
Cell 1 Cell 2 Cell 3 Cell 5
Cell 1 Cell 2 Cell 3 Cell 4
Cell 1 Cell 2 Cell 3 Cell 4 Cell 5
Cell 1 Cell 2 Cell 3 Cell 4 Cell 5
Cell 1 Cell 2 Cell 3 Cell 4 Cell 5
This is the Table Footer

On the CSS

  • Add to the table to avoid double borders:
    • border-collapse: collapse;
    • border-spacing: 0;
  • Add borders and paddings to the th and td.
    • th, td { border : solid 1px #000000; }
  • To change the background of every other row use:
    • tr:nth-child(even){ background: #ccc; }

Page Paddings and Margins

Paddings and margins have 4 values: top, right, bottom, left. You can assign the values individually by using padding-top:, padding-right, etc. Values are applied clockwise.

Overriding default browser styles

  • The body has a default margin of 8px.
  • p tags have a 1em margin on top and bottom.
  • box-sizingdetermines if the padding will be applied inside the element, or outside. The default is content-box which adds the size of the padding to the element's size. Changing it to border-box adds the space inside the elements's available space.
  • Default Browser Styles
margins and paddings graphic

Centering content


Centering Text:

  • use text-align:center;

Centering content

  • Place the content you want to center in a container (div, section, etc)
  • Add a width to both divs (One will be smaller than the other)
  • Add auto margin to the left and right to the inside container, and let css calculate the distance.margin: 0 auto;
This is the content

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Totam earum recusandae eaque dignissimos id quas architecto blanditiis adipisci quo nihil doloribus saepe accusamus laboriosam laborum, labore iure voluptatum sapiente consectetur.

A note on Browsers

  • Blink – Used in Google Chrome, and Opera browsers.
  • WebKit – Used in Safari browsers.
  • Gecko – Used in Mozilla Firefox browsers.
  • Trident – Used in Internet Explorer browsers.
  • EdgeHTML – Used in Edge browsers.