HOWTO.front_end_development - raynaldmo/HOWTO GitHub Wiki

Front End Development

Required Skills

  • HTML5
  • CSS
    • Flexbox
    • CSS Grid
    • Be able to build a layout (2-column, 3-column etc)
    • Know how these properties work : display, position, z-index, flex, float
  • JavaScript (ES6)
    • let and const
    • Closures
    • ES6 Classes
    • Prototypal Inheritance
    • Promises
    • Fetch API
    • Async Await
    • Arrow Functions
    • ES6 Modules
    • Template Strings
    • Spread Operator
  • JQuery
  • Git and GitHub (or BitBucket)
  • Package Management
    • npm or yarn
  • Linux (command line)
  • WebPack or Parcel
  • Know at least 1 JS Framework (component based)
    • React.js
    • Vue.js
    • etc.

Optional Skills

  • SVG or Canvas
  • Gulp or Grunt
  • Service Workers
  • Test Framework
    • Jasmine
    • Mocha
    • etc.
  • Mobile Development
    • React Native

Frameworks

Templates

Cascading Style Sheets (CSS)


CSS Topics


  • HTML Elements
  • Including CSS in Page
  • Selectors
  • Cascade, Specificity and Inheritance
  • Units
  • Box Model
    • Margin collapsing
  • Layout
    • Floats
    • Positioning
    • Stacking context
    • Flexbox
    • Grid
  • Responsive Layout
  • Modular CSS
  • Pattern Libraries
  • SASS

HTML Elements

  • Elements are the basis of HTML document structure (p, div, img, span, h1)
  • Every HTML element generates a box that contains the element's content
  • Replaced elements also generate boxes in their display

Semantic Elements

  • <header> - Header of the Layout
  • <footer> - Footer of the Layout
  • <nav> - Navigation area
  • <main> - The main content area
  • <article> - Publication area
  • <section> - Grouped area
  • <aside> - Sidebar/secondary content
<!-- Replaced elements -->
<img src="image.jpg">
<input type="radio">

<!-- Non-replaced elements -->
<p> <div> <span>
  • Margins create extra space around an element
  • Padding creates extra space within an element

Unicode Characters in HTML

  • Unicode characters can be used to display various symbols and icons directly within HTML, offering a lightweight alternative to image-based icons or icon fonts
  • See HTML UTF-8 Symbols
  • On Mac CTL-CMD-Space will bring up the Symbol popover - from there you can select the symbol
    instead of manually typing the Unicode hex code

HTML Element Attributes

  • HTML elememt attributes provide additional information about HTML elements
  • All HTML elements can have attributes
  • Attributes provide additional information about elements
  • Attributes are always specified in the start tag
  • Attributes usually come in name/value pairs like: name="value"
  • Example attributes:
  • id
  • class
  • title
  • src
  • style
  • src
  • width
  • height
  • href

Display Roles

  • Block level element display: block
    • Expand vertically to hold their contents
    • Generate breaks before and after element box
    • Example elements: h1, div, p, li
    • Unless given a specific width, always expand horizontally to fit inside parent container
    • Note that <div> has no default styling by browser (user agent)
  • Inline level element display: inline
    • Generate an element box within a line of text and do not break up that flow
    • Example elements: a, span, img, strong, em, input elements
    • Appear within content of another element
      • Ignores margin-top, margin-bottom, width, height properties
      • Accepts margin-left, margin-right
      • Accepts padding property
  • Inline level block element display: inline-block
    • Same behavior as Inline level elements but accepts all margin properties (top, right, bottom, left) width, height properties

Including CSS in Page

Inline Style

<!-- style is an HTML attribute -->
<h1 style="color:white; background-color:#333;">Recipe Finder</h1>

HTML Style Element <style>

  • styles apply to all <header> elements on page
<style>
header {
   color: white;
   background-color: #333;
   font-size: 1.5em;
}
</style>

@ import

  • Multiple CSS files loaded via @import will often take longer to download
    • So in general don't use this method
<style>
  @import url (css/style.css);
</style>

Link Element <link>

  • Recommended/Best way to include CSS in a web page
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My Web Site</title>
    <link href="css/style.css" rel="stylesheet">
  </head>
  <body>
  <!-- Content -->
  </body>
</html>

Selectors


  • CSS selector defines which portion of HTML document CSS Rule targets
  • selector along with property-value declaration is called a CSS Rule
/* CSS Rule */         
selector {           
 property: value; /* declaration */      
 property: value; /* declaration */
 ...    
}

/* CSS Rule */
h1 {                    
  color: white; 
  background-color: #333;
  font-size: 1.5em;
} 

Basic Selectors

Universal Selector

  • Selects all elements on a page
* {color: green; font-size: 1 em;}

Element Type Selector

  • Selects all HTML elements of the given type
ul {list-style: none; border: solid 1px #ccc;}

ID Selector

  • Selects HTML elements with given id attribute
  • Only one element on a page should have a given id
#container {
  width: 960px;
  margin: 0 auto;
}
<div id="container"> </div>

Page Linking

  • ID selector can be used for internal page linking
  • In the below example, clicking on the "Intro" link will navigate you to the indicated section
<a href="#intro">Intro</a>
....
<section id="#intro">
  <p>This is the intro section.</p>
</section>

Class Selector

  • Select HTML elements with given class attribute
  • Multiple elements on a page can have the same class attribute
  • Elements can have multiple classes
.box {
  margin: 10px;		
  width: 100px;
  height: 100px
  background-color: gray;
}

.box1 {
  background-color: red;
}

.box2 {
  background-color: green;
}

.box3 {
  background-color: blue;
}
<div class="box">box</div>
<!-- <divs> element with multiple classes -->
<div class="box box1">box1</div>
<div class="box box2">box2</div>
<div class="box box3">box3</div>

Combinators

  • Lets you combine two or more selectors so you can be more specific in selection

Descendant Combinator

/* note space between #container and .box selectors */	
#container .box {  		
  float: left;			
  padding-bottom: 15px;		
}

/* note space between .message and .error selector */
.message .error {
  color: red;
}

/* note space between p and class selector */
p .blue {color: blue;}

/* Target all elements with type attribute "text" that are 
 * inside element with id = "form1" 
*/
#form1 [type="text"] {
  border: solid 1px #ccc;
}
<div id="container">
  <div class="box"> </div>
</div>

<p>This line is <span class="blue">blue</span></p>
<p class='message'>Error message<span class=error">This is the error</span></p>

Child Combinator (>)

  • Similar to Descendant Selector but targets immediate child elements
#container >  .box {		
  color: red;
}
<div id="container">
  Content
  <div class="box">
    Box 1 <!-- Box 1 is child and will be red -->
  </div>
  <div>
    <div class="box">
      Box 2 <!-- Box is not child -->
    </div>
  </div>
</div>							

General Sibling Combinator (~)

  • Selected elements are next to each other
h2 ~ p {		
 color: red;
}
<!-- Above style applies to Line 1 and Line 2 but not Line 3 -->
<h2>Title</h2>
<p>Line 1</p>		
<p>Line 2</p>
<div class="box">
 <p>Line 3</p>  <!-- Not sibling of <h2> -->
</div>

Adjacent Sibling Selector (+)

  • Almost same as General Sibling Combinator (~) but must be a immediate sibling
p + p {		    
  text-indent: 1.5em;
  margin-bottom: 0;
}
<h2>Title</h2>
<p>Line 1</p>
<p>Line 2</p>    <!-- style applies here -->
<p>Line 3</p>	 <!-- style applies here -->
<div class="box">
  <p> Line 4 </p>
  <p> Line 5 </p>  <!-- style applies here -->
</div>

Compound Selector

  • Multiple Basic Selectors can be combined with one or more other selectors
/* compound selectors */
/* note no space between selectors */
p.blue {color: blue;}
div.is-active.dropdown {display: block;}
#header.callout { color: yellow; }
.class1.class2 { font: 1.2em serif; }
<p class="blue"> Line 1 </p>
<div class="dropdown is-active">
<h1 id="header" class="callout">Header</h1>
<input type="text" class="class1 class2">

Attribute Selector

  • Attribute selectors
  • Targets elements based on presence and/or value of HTML attributes and is declared using square brackets
/* input is HTML element */
/* type is a HTML element attribute */
/* text is the attribute value and can use single/double or no quotes */
input[type="text"] {  
  background-color: #444;
  width: 200px
}
<input type="text" id="id" name="name">
/* Matches all input elements with attribute of type regardless of value */
input[type] {
  margin: 2%  
  width: 100px;
}  
			
/* Also attributes may be specified by itself w/o element */
[attribute] {
  ....
}

Pseudo-Class Selector

  • A pseudo-class uses a colon character to identify a state that an element might be in
    • Ex: the state of being hovered, or the state of being activated
a:hover {
  color: white
}

/* pseudo-states */
:active, :checked, :enabled
:first, :first-child, :first-of-type
:focus, :hover, :last-child
:last-of-type, :link
:nth-child()
:nth-last-child()
:nth-last-of-type()
:nth-of-type()
:only-child, :only-of-type
  • Example using pseudo-class selector
tbody tr:nth-child(2n + 1) {
  background-color: lightblue;
}
<table>
  <thead>
   <tr>
     <th>
       Name
     </th>
     <th>
       Email
     </th>
   <tr>
  </thead>
  <tbody>
    <tr>
      <td>
       Row 1 Col 1
      </td>
      <td>
       Row 1 Col 2
      </td>
    </tr>
    <tr>
      <td>
       Row 2 Col 1
      </td>
      <td>
       Row 2 Col 2
      </td>
    </tr>
  </tbody>
</table>

Pseudo-Element Selector (single colon ok too)

  • Pseudo-elements are similar to pseudo-classes but instead of selecting elements with a special state, they target a certain part of an element
  • They target only portions of an element or even inject content into the page where the markup defines none
/* Note double colon after selector - single colon works too */
selector::pseudo-element {	
  property: value;
}

/* pseudo-elements */
::after
::before
::first-letter
::first-line
::selection
::placeholder	
			
p::first-letter {
  color: red;
  fontsize: 125%
}

Multiple Selectors

  • Combine multiple selectors in a single rule set
  • Use commas to separate selectors
/* All p, div elements and elements with box class will have black text color */
p, div, .box {
  color: black;
}

Selector Properties & Values

Properties

  • Example properties color, background-color, margin, display, width, font-size, height
  • See CSS Reference

Values

  • Four Value Types
    • Pre-defined Options
    selector {
      display: block;
    }
    selector {
      overflow: auto;
    }
    • Colors
    selector {
     background: red:
     ...
     color: #fa923f;
     ...
     color: #ccc;
    }
    • Length, Sizes & Numbers
    selector {
     height: 100px;
     width: 20%;
     order: 1;
    }
    • Functions
    selector {
     background: url(...);
     transform: scale(...);
    }

Inheritance, Cascade, Selector Specificity


Key Concepts

  • Parent styles are generally inherited
  • Multiple rules can apply to one element
  • Specificity resolves "multiple rules" conflict
  • Inheritance defaults can be changed - use inherit keyword for value

Inheritance

  • Inheritance is mechanism by which some property values are passed on from an element to its descendants
  • Styles are applied to element and descendants
/* Example */
/* Child node element (<em>) inherits color property value
 * (Color is an inheritable property)  
 * Otherwise <em> text would be black and would need to be styled separately
 */
h1 { color:red; }
<h1> This is a <em> heading </em> </h1>
  • color, font, font-size are inheritable properties
  • Most of the box-model properties including margins, padding, backgrounds, and borders are not inherited
  • Inherited values have no specificity, universal selector (with zero specificity) can override them

Cascade

  • In CSS, multiple rules/styles may apply to the same element and all the rules are taken into account in determining the element's final styling
    • This is what is meant by Cascade/Cascading - this may lead to conflicts though
  • Cascade rules is how CSS resolves element styling conflicts

Selector Specificity

  • Each selector is assigned a weight
  • In general (along with overall Cascade Rules), the style specified by the selector with the highest weight gets applied to the element

Element Style Determination

  • Element style is determined by:
    • Weight (normal and !important)
    • Specificity
    • Declaration source and order
/* Example */
/* Cascade rules will determine text color of h1 element */
/* In the below case h1 content will be red since the selector (h1) specificity 
 * is the same but color:red is the last declaration.
*/
h1 {
  color: blue;
}

h1 {
  color: red;
}

Weight

  • Weight can be normal or !important
/* Examples */
p.dark {color: #333 !important; background: white;}
p.dark {color: #333 !important; background: white !important;}
p.light {color: yellow; font: smaller Times, serif !important;}
Selector Specificity
  • For conflicting property values, Selector Specificity determines which value takes effect
  • Specificity is expressed in four parts 0, 0, 0, 0
    • Inline style :add 1, 0, 0, 0
    • ID attribute in selector :add 0, 1, 0, 0
    • Class attribute value, attribute selection or pseudo-class in selector :add 0, 0, 1, 0
    • Element or pseudo-element in selector :add 0, 0, 0, 1
    • Universal selector in selector :add 0, 0, 0, 0 (don't add anything)
    • Combinator selector (add individual selector weight)
    • Inherited values have no specificity, universal selector (with zero specificity) can override them
/* Conflicting color values */
/* Example 1 */
h1 {color: red;}	   /*  0, 0, 0, 1 */
body h1 {color: green;}	   /*  0, 0, 0, 2 (winner) */

/* Example 2 */
/* In this example even though the silver color declaration is after
 * the purple color declaration, h2 will be purple because that selector has
 * has higher specificity. Selector ordering (within same stylesheet) only
 * comes into play when selectors have the same specificity. In these cases
 * the last selector wins.
 */
h2.grape {color: purple;}  /* 0, 0, 1, 1 (winner) */
h2 {color: silver;}	   /* 0, 0, 0, 1 */

/* Example 3 */
html > body table tr[id="totals"] td ul > li {  /* 0, 0, 1, 7 */
  color: maroon;
}
li#answer {color : navy;}	 /*  0, 1, 0, 1 (winner) */
/* Example 4 - Inline style */
h1#meadow {color: red;}	    /* 0, 1, 0, 1 */
<!-- Meadow color will be green -->
<h1 id="meadow" style="color: green;">Meadow</h1>   <!-- 1, 0, 0, 0 -->
/* Example 5 */
/* Using !important to force a style */
p.dark {
  color: #333 !important; 
  background: white;
}

p.light {
  color: yellow; 
  font: smaller Times, serif !important;
}
Declaration Source
  • Inline style overrides
    • Embedded style sheet overrides
      • External style sheet

Link Styles

  • Use LVHA rule for link <a> styles
/* Order rules using the following order */
a:link {
  color: xxx;
}
a:visited {
  // ...
}
a:hover {
  // ...
}
a:active {
  // ...
}

/* Each rule has same specificity (0, 0, 1, 0) */
/* When unvisited link is being clicked :active is matched */
/* Afterward :visited is matched */
/* When hovering :hover is matched */

Cascade Algorithm

  • Find all rules that contain a selector that matches a given element

  • Sort by explicit weight all declarations applying to the element

    • Rules marked !important are given higher weight
  • Sort by origin all declarations applying to a given element

    • Origins are: author, reader, and user agent
    • Normally author's styles win out over reader's styles
    • but !important reader styles win out over any other styles
      • including !important author styles
    • Both author and reader styles override the user agent's default styles
  • Sort by specificity all declarations applying to a given element

    • Elements with a higher specificity have more weight than those with lower specificity
  • Sort by order all declarations applying to a given element

    • The later a declaration appears in the style sheet or document, the more weight it is given
    • Declarations that appear in an imported style sheet are considered to come before all declarations within the style sheet that imports them.

Dimensions, Sizes & Units


Properties that take a unit value

  • font-size, width, height, padding, border, margin, top, bottom. left, right

Absolute Units

  • These units mostly ignore user settings
  • pixels, inches, cm, mm, pt, pica
  • For web use only pixels are used
  • pixel size was originally based on pixel size of early computer monitors
  • pixel size is now a CSS standard measurement and is not related to pixels on your screen
  • Using pixels for measurement (margin, padding, font-size) isn't good practice though:
    • If user changes font size via his/her browser settings, content font size won't change since the size is fixed (in pixels)
    • Use rem or em for font size

Font Relative Units

  • These units adjust to default font size
  • ems and rems
  • 1 em is defined as the font size of the current element
    • If current element font size is not specified then font size is taken from closest ancestor element
  • 1 rem (root em) is relative to the font size of the root element (:root/html element)
    • Most browsers set the root/default font size to 16px
  • Using rem for font size sets the font size relative to the browsers base font-size
    • This allows font size to scale when user changes font size via browser settings
    • For example, when using Chrome browser, go to Settings -> Font size to change font size
    • User can also use Ctl/Cmd + or Ctl/Cmd - to zoom in/out
      • This zooms the entire page and is independent of font size change via browser settings
/* Set default font size to 18px */
/* Over-rides browser default setting of 16px */
/* Content without a specified font size (either by specific rule or browser default) will take this value */
:root {
  font-size: 125%;
}
  • Use rem (preferred) or em for padding, margin, height, border radius
    • These settings will scale evenly with the element font size
    • (Percentages can be used for container widths (when necessary))
  • Use rem for font sizes
    • This will ensure that font sizes correctly scale if user changes font size via browser settings
  • Use px for borders and box-shadow
  • The exception to the above rules is when a specific desired layout requires that a particular property (width etc.) be specified as a fixed size (i.e in px)

Percentages

  • Percentages are also considered relative units

  • Three rules to remember concerning percentages

  • Rule #1

    • If element has position: fixed, containing block is viewport
    • Percentage value is based on viewport width/height
  • Rule #2

    • If element has position: absolute, containing block is an ancestor element
    • Ancestor element is any element that has position: relative, fixed, sticky
    • If no such ancestor element exist, containing block is viewport
    • Percentage value is based on ancestor content width/height + padding
  • Rule #3

    • If element has position: relative or position: static, containing block is an ancestor element
    • Ancestor element is closest block level element
    • If no such ancestor element exist, containing block is viewport
    • Percentage value is based on ancestor content width/height

Fixes for setting height to a percentage value

  • At times specifying height as a percentage value may not work
<!-- Sample HTML -->
<div class="backdrop"></div>
  • Solution #1
    • body and html elements containers must specify height:100%
/* CSS */
html {
  ...
  height: 100%;
  ...
}

body {
  ...
  height: 100%;
  ...
}

.backdrop  {
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5);
}
  • Solution #2
    • Set element position to position: absolute or position: fixed
    • No need to set height:100% on body or html elements
.backdrop  {
  position: absolute;  /* position: fixed works too */
  width: 100%;    /* or 100vw */
  height: 100%;   /* or 100vh */
  background-color: rgba(0,0,0,0.5);
}

Viewport Relative Units vw & vh

  • Define lengths relative to the browser’s viewport

    • vh 1/100th of the viewport height
    • vw 1/100th of the viewport width
    • vmin 1/100th of the smaller dimension, height or width (IE9 supports vm instead of vmin)
    • vmax 1/100th of the larger dimension, height or width (not supported in IE or, at the time of writing, Edge)
  • viewport-relative lengths are great for things like making a large hero image fill the screen

    • Your image can be inside a long container, but setting the image height: 100vh, makes it exactly the height of the viewport
  • viewport-relative units are a newer feature for most browsers - so there maybe some quirks/bugs

Understanding min-width, min-height, max-width, max-height properties

  • Use max-width to constrain content (most commonly images) from getting too wide as viewport widens
  • Always use with width property
<!-- HTML -->
<div class="image-container">
  <img src="image.jpg" class="image">
</div>

/* Example CSS */
.image-container {
  ...
  width: 65%;
  max-width: 580px;  /* Limit image to be no wider than 580px */
  display: inline-block;
  ...
}

.image {
  width: 100%
}
  • Use min-width to constrain content from getting too narrow as viewport narrows
  • Always use with width property

calc()

  • Use calc() function to calculate CSS property values
/* property: calc(expression) */
width: calc(100% - 80px);

Summary - Recommended Unit to Use for Different Properties

  • font-size (root element): % or don't specify
  • font-size: rem (em for specific children)
  • padding: rem
  • margin: rem
  • border: px
  • width: % or vw
  • max-width: % or px
  • min-width: % or px
  • height: % or vh
  • top: %
  • bottom: %
  • left: %
  • right: %

Unit-less Measurements

/* Example using line-height */
...
line-height: 1.7;
...

Box Model


  • The Box Model refers to the (usually) invisible rectangular area that is created for each HTML element
  • When you specify the width and/or height of an element, you’re setting the content size
    • Any padding, border, and margin will be added to the content size
  • Box Model has four basic components
    • Content
    • Padding
    • Border
    • Margin
  • Every web page element has Box Model components
    • Different elements may have different default characteristics (browser dependent) Box Model
  1. Content
  • Holds content (text, images, video)
    • Content width, height, padding and borders will increase "content box"
  1. Padding
  • Padding is space around content
    • Creates space between content and border
  • Defined using padding property
  • **Use padding to give room for all elements inside the box **
/* Padding property */
selector {
  padding-top: 20x;
  padding-right: 10px;
  padding-botton: 10px;
  padding-left: 30px:
}

/* shorthand property */
padding: 20px 10px 10px 30px;
  1. Border
  • Border of an element is defined using the border property
/* shorthand property that defines the element's border-width
 * border-style, and border-color
 */
border: 4px dashed orange
  1. Margin
  • Margin is the portion of an element exists outside the element's border
  • Use margin to create space between an element and surrounding elements
  • Most block elements have default margin settings set by the browser.
  • Think of this margin as being "part" of the element and independent of the element's box
/* Margin property */
selector {
  margin-top: 20x;
  margin-right: 10px;
  margin-botton: 10px;
  margin-left: 30px:
}

/* shorthand property */
margin: 20px 10px 10px 30px;

box-sizing property

  • box-sizing property controls element width and height calculation
  • Set box-sizing: content-box to exclude border and padding in setting
    element width and height
selector {
  ...
  box-sizing: content-box; /* default setting */
}
  • Setting box-sizing: border-box to an element changes the box model
  • Setting element height or width will control the size of the entire element, including its padding and border
  • This makes the space an element takes more predictable
/* Set box-sizing property to border-box to include border and padding in setting
 * element width and height
 */
selector {
  ...
  box-sizing: border-box;
}

/* Use this code to set all elements to border-box */
:root {
  box-sizing: border-box;
}

*, ::before, ::after {
  box-sizing: inherit;
}
  • Box Model - Border Box

Box Model - Border Box

Overflow

  • When a content block no longer fits its container we get overflow

(OVERFLOW MODEL ILLUSTRATION)

  • Overflow property applies to container element to control how content is displayed
selector {
 ...
 overflow: scroll /* also hidden and auto */
}

"Lobotomized owl selector"

  • Use to automatically add top margins to elements throughout a page. This is to ensure consistent spacing between stacked elements.
    • This selector targets any element that immediately follows any other element
body * + * {
  margin-top: 1.5em;
}

Resources

Floats


/* Example 1 
 * image is "pushed" left and other element flow around image 
 */
/* HTML */
<img src="image.png">
<p>Text.......</p>

/* CSS */
img {
  float: left;
  margin-right: 1em;
}
/* Example 2 
 * image is "pushed" right and other element "flow" around image 
 */
/* HTML */
<img src="image.png">
<p>Text.......</p>

/* CSS */
img {
  float: right;
  margin-left: 1em;
}

Positioning


  • Allows you to place elements exactly where you want
  • Elements can be made to overlap each other
  • Element position is controlled using position property

Position Static

  • Element follows normal document flow - this is the default for all elements
div {
  position: static;
}

Position Fixed

  • Element is completely removed from normal document flow
  • Works the same for block and inline elements
    • Element will behave as an inline-block element
  • Positions element relative to the viewport (always!)
    • Viewport is containing block or (positioning context)
  • Element stays in same position even after scrolling
/* Fix navigation bar to top of viewport */
.main-nav { 
  position: fixed; 
  top: 0; 
  left: 0;
  width: 100%
}
/* Fix footer div bar to bottom of viewport */
div > footer { 
  position: fixed; 
  bottom: 0; 
  width: 100%
}

Position Absolute

  • Element is completely removed from normal document flow
  • containing block is closest positioned ancestor element
  • If no ancestor element is positioned then html element becomes containing block (or positioning context)
/* HTML */
<div class=parent>
  <div class="child-1">Box 1 </div>
</div>

/* CSS */
/* containing block */
.parent { 
  position: fixed;  /* positioned */
  top: 3em;
  bottom: 3em;
  left: 20%;
  right: 20%;
}

/* absolute positioned element */
.parent .child-1 {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 50px;
  height: 50px;
}

Position Relative

  • Positioning context is the element itself
  • Element is moved from its current position using top, left, bottom, right properties
  • Can be used to make elements overlap
  • Typically used though to establish containing block/positioning context for absolute positioned element(s)
/* HTML */
<div class="parent">
  <div class="child-1">
  </div>
</div>

/* CSS */			
.parent {
  ...
  position: relative; /* set wrapper div as new containing block */
  overflow: hidden;   /* hide element if positioning falls outside parent container - auto works too */
  ...
}

.child-1 {
 position: absolute:
 left: 3em;
 width: 6.25em;
 height: 6.25em;
}

Position Sticky

  • Hybrid of relative and fixed positioning
  • Positioning context is viewport
  • When scrolling, element will remain in fixed position (relative to viewport) until parent container is scrolled out of view
  • Not well supported by older browsers
/* HTML */
<div class="parent">
  <div class="child-1">
  </div>
</div>

/* CSS */			
.parent {
  ...
}

.child-1 {
 width: 100px;
 height: 100px;
 background-color: yellow;
 position: sticky:
 top: 0;
}

z-index

  • z-index property controls the vertical stacking order of elements that overlap
    • Default value is auto (0)
  • Only works on positioned elements those with a position value other than static
  • Adding z-index property to an element establishes a stacking context
  • For elements with the same z-index, the stacking order is determined by their order in the HTML page
    • Elements appearing later will be rendered on top
  • Stacking contexts determines which elements are in front of other elements
    • Stacking context affects the behavior of an element's z-index value

Text Fonts


Generic & Font Families

  • Website text can be rendered in literally hundreds of different fonts
  • There are several Generic font families serif, sans-serif, cursive, monospace fantasy
  • Each Generic font family has specific font family variations
  • serif
    • Times New Roman, Georgia
  • sans-serif
    • Helvetica, Verdana
  • cursive
    • Brush Script, Mistral
  • monospace (same as fixed-width)
    • Courier New, Lucida Bright
  • fantasy

Font Selection

  • Three options to specify a font
    • No specified font
      • In this instance the browser default will be used
      • In Chrome browser go to Settings -> Customize fonts
      • "Standard font" will be the default font used
    • Generic family (serif, sans-serif etc.)
    • Specific font family (Times, Verdana etc.)
  • Font family can be stored/retrieved from:
    • User's computer (Locally installed fonts - OS dependent)
    • Web fonts (Use Google Fonts, Adobe Fonts, FontSquirrel)
    • Our website server (Use @font-face CSS rule)
  • Best practice is to use Web fonts and not rely on locally installed fonts

Working with Google Fonts

  • To add Google Fonts to site/page:
  • Navigate to Google Fonts
  • Search for or select font
    • Optional: Choose desired font-weight and/or font style
  • Click on red + sign to select the font
  • "Family Selected" window will appear at bottom of page
  • Open window to see instructions for adding font
  • Instructions will show HTML and CSS to add
  • See below examples:
<!-- Add to HTML page -->
...
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono" rel="stylesheet">
...
/* Add to CSS stylesheet */
...
@import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');
...

/* Use font on an element */
body {
  font-family: 'Roboto Mono', monospace;
}

Working with @font-face CSS rule

  • Use @font-face rule to import and use custom fonts directly from website server rather than a third-party server or CDN
  • Follow "Working with Google Fonts" section to select font and download font files
  • See below example using Anonymous Pro font
/* packages.css */
/* Custom font only used on packages page */
/* Use @font-face rule to grab font from our website server
 * rather than a third-party server or CDN
*/
@font-face {
  font-family: 'Anonymous Pro';
  src: url('../fonts/AnonymousPro-Regular.ttf');
  /* Use this font-display property to control how text is rendered if there 
   * is excessive latency downloading the font
   */
  font-display: auto;  
}

@font-face {
  font-family: 'Anonymous Pro';
  src: url('../fonts/AnonymousPro-Bold.ttf');
  font-weight: 700;
}

@font-face {
  font-family: 'Anonymous Pro';
  src: url('../fonts/AnonymousPro-BoldItalic.ttf');
  font-weight: 700;
  font-style: italic;
}

@font-face {
  font-family: 'Anonymous Pro';
  src: url('../fonts/AnonymousPro-Italic.ttf');
  font-style: italic;
}
...
/* Normal weight */
.package__title {
  font-family: 'Anonymous Pro', sans-serif;
}

/* Bold */
.package__title {
  font-family: 'Anonymous Pro', sans-serif;
  font-weight: 700;
}

Font Formats

  • There are several types of Font Formats
    • TTF/OTF - TrueType and OpenType (.ttf)
    • WOFF - Web Open Font Format (.woff)
    • WOFF 2.0 - Web Open Font Format (.woff2)
    • EOT - Embedded OpenType fonts (.eot) (Only supported by IE)
  • Different browsers have different level of support for the various formats
  • Use @font-face rule as below to specify the various formats
...
/* Specify all formats in order to cover as many browsers as possible */
@font-face {
  font-family: 'Anonymous Pro';
  src: url('../fonts/AnonymousPro-Regular.woff2') format('woff2'),
       url('../fonts/AnonymousPro-Regular.woff') format('woff'),
       url('../fonts/AnonymousPro-Regular.ttf') format('truetype');
}
...

Font Properties

  • The following properties can be applied to any text
  • font-family
  • font-size
  • font-weight
  • font-style
  • font-variant
  • font-stretch
  • letter-spacing
  • line-height
  • whitespace
  • text-decoration
  • text-shadow

Font Shorthand - font

  • Use font CSS property as a shorthand for font-style, font-variant, font-weight, font-stretch, font-size, line-height, font-family
  • Alternatively, it sets an element's font to a system font.
Reference

MDN - font CSS property

Web Fonts

Icon Fonts


How to use Fontastic

  • Go to https://app.fontastic.me/ and login
  • By default the last created icon font set will be selected
    • For example FEDFont
  • Click on Publish and scroll down to "ICONS REFERENCE" to see icons in the set
  • Create new icon set
    • Use "Search icons..." box to find icons
    • Select icons
    • Click "Modify Font" to name icon set
    • Click Or Install Manually -> Download - This will download zip file
  • Refer to front-end-development project for example usage

Favicon


...
<!-- Sample code -->
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon">
<!-- Apple iOS icons -->
<!—- iPhone 57x57 -->
<link rel="apple-touch-icon" href="img/touch-icon-iphone.png"/>
<!—- iPad 72x72 -->
<link rel="apple-touch-icon" href="img/touch-icon-ipad.png" sizes="72x72"/>
<!—- iPhone Retina Display 114x114 -->
<link rel="apple-touch-icon" href="img/touch-icon-iphone-rd.png" sizes="114x114"/>
<!—- iPad Retina Display 144x144 -->
<link rel="apple-touch-icon" href="img/touch-icon-ipad-rd.png" sizes="144x144"/>
<link href="css/styles.css" rel="stylesheet"/>
...

Spinner Graphics

Images


Dummy Image Generator

Image Map Generator

Working with Stock Images

  • Use Unsplash for free stock images
  • Scale, crop and reduce image size using Pixlr
  • Also can use MacOS Preview to export image at reduced quality to reduce image size
  • ALTERNATIVE: Use Croppola

<img> tag vs background-image property

  • Using <img> tag for images is better for accessibility but more difficult to style
  • Using background-image property for an image makes image easier to position and size

Image Styling

  • How to center image horizontally within a div element
  • Image with <img> tag
  • Best practice is to always use container (<div> or other element) to wrap image
  • Image container must be block or inline-block element (for image to honor width or height setting)
  • To have image automatically adjust to viewport dimensions and maintain correct aspect ratio
    • Don't add width and height attributes to <img> tag
    • Set img { max-width: 100%; }
<div class='image-container'>
  <img src=image.png alt="Image">
</div>
/* Constrain image to a certain height */
.image-container {
   ...
   display: block; /* or inline-block */
   height: 50px;
   ...
}

/* Image will be constrained to height of 50px irrespective of actual height */
/* Image width will automatically scale to maintain original aspect ratio */
.image {
  height: 100%;
}

/* Constrain image to a certain width */
.image-container {
   ...
   display: block; /* or inline-block *;
   width: 80%;
   ...
}

/* Image height will automatically scale to maintain original aspect ratio */
img {
  max-width: 100%;
}

Background Images

selector {
...
  background: red; /* Set element background color */
}
  • background-image property sets a background image for an element
.hero-image {
  ...
  background-image: url(../images/freedom.jpg);
  ...
}
  • Use the following individual properties to control background images
background-color        /* Set a background color */
background-image        /* Set one or more background images */
background-position     /* Set initial image position relative to background position layer */
background-size         /* Set size of background image */
background-repeat       /* Defines how background image is repeated */
background-origin       /* Set background positioning area for background image */
background-clip         /* Defines whether background extends underneath border */
background-attachment   /* Sets the scrolling behavior of the background image */
  • Use background-size and background-position to control position and cropping within image container
  • background-size: contain is like zoom fit
    • contain adjusts image size to match the larger dimension among width and height
    • Image is scaled to fill the space without clipping nor distorting.
  • background-size: cover is like zoom fill
    • cover adjusts image size to match the smaller dimension among width and height
    • Image is scaled and cropped to fill the entire space without being distorted.
  • background-size: fill
    • Image will be stretched and distorted to completely fill the space.
/* Make image fill container and center image */
.container {
  ...
  background-image: url(../images/freedom.jpg);
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  ...
}
  • Use background-origin and background-clip to control how image renders when it has a border
  • Similar effect as box-sizing property
.container {
  ...
  background-origin: border-box;
  background-clip: border-box;
  ...
}
  • Use background-attachment: fixed to implement parallax scrolling effect with image

Gradients

  • Gradients let you display smooth transitions between two or more specified colors
  • CSS defines two types of gradients
    • Linear Gradients (goes down/up/left/right/diagonally)
    • Radial Gradients (defined by their center)
  • Gradient setting is specified using background-image property and either
    the linear-gradient() or radial-gradient() function
/* Simple linear gradient red on top, blue on bottom */
.container {
  background-image: linear-gradient(to bottom, red,blue);
}

Stacking Multiple Background Images

/* Example of stacked gradient, image and background color */
.hero-image {
  ...
  background-image: linear-gradient(to top, rgba(80, 68, 18, 0.5) 10%, transparent), url("../images/freedom.jpg");
  background-color: red;
 ...
}

Filters

  • MDN CSS Filter
  • filter property applies graphical effects like blur or color shift to an element
  • Filters are commonly used to adjust the rendering of images, backgrounds, and borders
/* Example grayscale filter */
.background-image {
 ...
 background-image: url("image.jpg")
 filter: grayscale(50%);
 ...
}

Scalable Vector Graphics (SVG)

  • How to Use SVG Images in CSS and HTML – A Tutorial for Beginners
  • Adding SVG to your pages
  • SVG is basically an image format
  • SVG is different then bitmap image formats like JPEG, PNG or GIF
    • SVG images can be created and edited with any text editor
    • SVG images can be searched, indexed, scripted, and compressed
    • SVG images are scalable
    • SVG images can be printed with high quality at any resolution
    • SVG images are zoomable
    • SVG graphics do NOT lose any quality if they are zoomed or resized
    • SVG is an open standard
    • SVG files are pure XML
  • Flash is comparable to SVG but FLASH is proprietary

Tables


<!-- HTML -->
<div class = "wrapper">
<table class = "tbl">
  <caption> My Table </caption>
  <thead>
    <tr>
     <th> Header 1 </th>
     <th> Header 2 </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> Row 1, Cell 1 </td>
      <td> Row 1, Cell 2 </td>
    </tr>
  </tbody>
</table>
</div>

/* CSS */
.tbl {
  border: 1px solid #000; 
  border-collapse:collapse;
}
	
.tbl td {			
  border: 1px solid black;		  
  text-align: left;
  padding: 0.3em;			   
  background-color: #f7f7f7;	  
}

.tbl th {			
  border: 1px solid black;		  
  text-align: left;
  padding: 0.3em		   
  background-color: #f7f7f7l
}

Table Styling w/o CSS

	<table border="1" align="center" bgcolor="lightblue" cellspacing="3" cellpadding="3" width="75%>

		<tr>
			<th> header 1 </th>
			<th> Header 2 </th>
		</tr>
		<tr>
			<td> Row ,1 Cell 1 </td>
			<td> Row 1, Cell 2 </td>
		</tr>
	</table>

		.table align-centers, left justifies, right justifies table wrt containing element
		.cellspacing - creates space between individual cells
		.cellpadding - creates space between conent and cell boarder
		.bgcolor - background color for entire table contents

Responsive Tables

TBD

Float Based Layouts


Centered - Fixed

<!-- HTML -->
<div class="wrapper">
  <div class="header">
    Branding
  </div					
  <div class="content">
    <p> Content </p>
  </div>
</div>

/* CSS */	
.wrapper {
  max-width: 920px; /* use max-width to prevent horizontal scrolling for smaller viewport sizes */
  margin: 0 auto; /* centers all page contents */
}

Two Column

/* HTML */
<div class="wrapper">
  <div class="header">
    <h2> Branding </h2>
  </div>

  <div class="content">
    <div class="main"> 	
      <p> Main Content...</p>
    </div>
   
   <div class="nav">
      <li><a href="#"> Home </a></li>
      <li><a href="#"> About </a></li>
   </div>
  </div>

  <div class="footer">
   Footer
  </div>

</div>

/* CSS */		
.wrapper {
  max-width: 920px; 
  margin: 0 auto /* liquid 920p.x/1250px, 76% */
}	

.content .main {
  width: 650px;
  float:right;
  padding-right: 20px;
  display: inline;
}

.content .nav {
  width: 220px;
  float: left;
  padding: 10px;
  display: inline;
}

Three Column

		<div class = "wrapper">
			<div class = "header">
			<h2> Branding </h2>
			</div>
		<div class ="content">
			<div class = "main">
				<div class = "col-1">
				<h3> Main Column 1 </h3>
				</div>
				<div class = "col-2">
				<h3> <Main Colummn 2 </h3>
				</div>
			</div>   <!--Main-->
				<div class = "nav">
				<h3> Links </h3>
				</div>
			<div class = "footer"> Footer </div>
		</div> <!--Content-->
		</div> <!--Wrapper-->
			
			.wrapper {width:920px; margin 0:auto}
			.main {width: 650px; float right; padding-right:20px}
			.col-1 {width: 370px; float left;}
			.col-2 {width: 230px; float right;}
			.nav {width: 2120px; float left; padding:10px}

Three Column Liquid

		- Same HTML
		- Use percentages (width) instead of fixed px

			.wrapper {width: 76%	/* 920px/1250px	76% */	(1250px is the max viewport width?)
				margin:auto;
				}
			.main {width: 72%;	/* 650px/920px	*/
				.....}
			.col-1 {width: 57%;	/* 370px/650px	*/
				.....}
			.col-2 {width: 33%;	/* 230px/650px	*/
				float:right;
				padding-right: 26% }
			.nav {width: 23%	/* 220px/920px	*/
				padding: 1%
				float:left}

Clearfix

  • Apply clearfix class to parent container of floated elements
/* HTML */	
<div class="main clearfix">
<div class="left"> Content </div>
<div class = "right"> Content </div>
</div>

/* CSS */
.left {
  float: left;
}

.right {
  float: right;
}

.clearfix:before, .clearfix:after {
  Content: " ";
  display:table
}

.clearfix:after {
  clear: both;
}

Summary

  • Floats originally existed to allow text to wrap around an element
    • Over time though it was used to do layout
  • Use a clearfix class to contain floated elements.
  • Understand the three tricks of a block formatting context (BFC)
    • Containing floats
    • Preventing margin collapse
    • Preventing text from wrapping around a floated element
    • Add overflow: auto to a container to create a BFC
  • Use the double container pattern to center page contents
.container {
  max-width: 1080px;
  margin: 0 auto; 
}
  • Use a Grid system to create flexible float based page layouts

Flexbox


Flexbox Overview

  • Flexbox (Flexible Box Layout) is a layout method for laying out elements in rows or columns
    • Elements "flex" to fill additional space and shrink to fit into smaller spaces
  • Removes the need to use floats for layout purposes
    • More predictable and offers far more specific control than floats
  • Removes the need to use display: inline-block for layout purposes
  • Supports vertical centering and equal height columns
  • Responsive and mobile friendly
  • Can change order of elements w/o editing source HTML
  • Supported by all major browsers (partial support in IE10)

Flexbox Principles

  • Use display: flex; to turn an element to a flex container
    • Container children are called flex items

Flexbox model

Flex Container

  • A flex container wraps Flex items
  • Any direct child within a flex container is a flex item
  • Flexbox Example
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Basic Flexbox Example </title>
  <style>
    .row {
      display: flex;
      flex-flow: row nowrap;
      background-color: #eee;
    }
    .child1 {
      flex: 1;
      background-color: yellowgreen;
    }

    .child2 {
      flex: 3.5;
      background-color: powderblue;
    }

    .child3 {
      flex: 1;
      background-color: olivedrab;
    }

    .child {;
      min-height: 100px;
    }
  </style>
</head>
<body>
    <header>Header</header>
    <section class="row">    <====== Flex container
      <div class="child child1">Child1</div>  <===== Flex item
        <div class="grand-child">Grand-child</div> <===== Not Flex item
      <div class="child child2">Child2</div>  <===== Flex item
      <div class="child child3">Child3</div>  <===== Flex item
    </section>
    <footer>Footer</footer>
</body>
</html>
  • Flex containers can be nested
<section class="row">  <!-- Flexbox container -->
  <div class="child child1">Child1</div>
  <div class="child child2">Child2</div>
  <div class="child child3">Child3</div>
  <aside class="row">  <!-- Flexbox container -->
   <div class="flex-item">Flex item 1</div>
    <div class="flex-item">Flex item 2</div>
  </aside>
</section>
  • Flex containers have 6 defined properties
    • flex-direction - defines in which direction (row or column) the container wants to stack the flex items
    • flex-wrap - specifies whether the flex items should wrap or not
    • flex-flow - shorthand property for setting both the flex-direction and flex-wrap
    • justify-content - defines flex item position along main axis)
    • align-items - defines flex item position along cross axis
    • align-content - used to align flex items
.container {
  display:         /* flex, inline-flex */
  flex-direction:  /* row (default), row-reverse, column, column-reverse */
  flex-wrap:       /* no-wrap (default), wrap, wrap-reverse */
  flex-flow:       /* shorthand for <flex-direction> <flex-wrap>  row nowrap (default) */
  justify-content: /* flex-start (default), flex-end, center, space-between, space-around */
  align-items:     /* flex-start, flex-end, center, stretch (default), baseline */
  align-content:   /* flex-start, flex-end, center, stretch (default), space-between, space-around */
}

Flex Item

  • Flex items also have six defined properties
    • flex-grow - specifies how much a flex item will grow relative to rest of flex items
    • flex-shrink - specifies how much a flex item will shrink relative to rest of flex items
    • flex-basis - specifies the initial length (px, auto, %) of a flex item
    • flex - shorthand property for the flex-grow, flex-shrink, and flex-basis properties
    • align-self - defines flex item position for specific item along cross axis, can over-ride align-items
    • order - specifies the order of the flex items, item with smallest order is positioned first
.flex-item {
  flex-grow:    /* integer  default 0, use > 1 to allocate unused space (width or height) to item */
  flex-shrink:  /* integer  default 1, use 0 to prevent item from shrinking below its specified width */
  flex-basis:   /* <length> or <percent> or auto (default) , length value (px) will override fixed width value (width: xxx px) */
                /* % value refers to flex container width for row flex-direction or height for column flex-direction */
  flex:         /* shorthand for <flex-grow> <flex-shrink> <flex-basis>  0 1 auto (default) */
  align-self:   /* auto (default), flex-start, flex-end, center, stretch, baseline */
  order:        /* integer  default 0 */
}

Summary

  • Use Flexbox to control layout of a row or column of content
    • For overall layout of a complete page use CSS Grid
  • Flexbox automatically creates columns of equal height
  • In general, to implement a Flexbox
    • Identify a container and its items
    • Use display: flex; on the container
      • Autoprefixer can simplify flexbox support for older browsers
    • Set desired flex property values on the container
    • Fine-tune flex item size by setting width, height, margins and/or flex item property values
  • Flex container:
    • Use justify-content property to control how the flex-items are distributed along the main axis
    • Use align-items property to control how the flex-items are distributed along the cross axis
      • align-items or align-self can vertically center a flex item inside its flex container
  • Flex items:
    • Use flex property to specify combination of flex item sizes
    • Only direct child elements of flex-container are flex items
  • Use nested flexboxes to piece together more complicated layouts
  • When using flexbox, media queries will most likely still be necessary to make content look good as viewport width changes

CSS Grid


Grid Basics

  • A Grid is basically a pattern, used by graphic and web designers to line up design elements to help create a consistent flow and symmetrical layouts
  • Grids are broken down into equal width and evenly spaced columns
  • Rows are added as a guide, to line up components horizontally as well
  • Gutters, the space between the rows or columns, are usually added to allow for consistent spacing between columns
  • Page components (HTML markup) are placed into the grid columns
  • Bootstrap uses a Grid System

Flexbox vs CSS Grid

  • Flexbox was designed for one dimensional layouts, either row or column
    • Rows and columns can be created by wrapping flex items or nesting flex containers
      but this isn't best practice though especially for complex layouts
    • Flexbox is most useful for space distribution for items on the same row or column
    • A good use-case of Flexbox would be for a horizontal or vertical navbar design
  • CSS Grid is better for working with rows and columns at the same time
    • Grid aligns items in both dimensions - row and column
    • Grid is most useful for layouts that require more row / column control i.e complex layouts
  • Flexbox and Grid can be used simultaneously

Grid Container

  • A Grid Layout must have a parent element with display: grid or display: inline-grid
  • Direct child element(s) of the grid container automatically becomes a grid item
  • NOTE: Child elements with position property other than static (relative, fixed, absolute, sticky) will not be grid items
    • Only direct child elements that are in normal document flow are grid items
  • Use Firefox Dev tools -> Layout for visual grid display

Grid Container Properties

display: // grid, inline-grid
grid-template-columns: px, %, repeat(), fr
grid-template-rows
grid-template-areas
grid-column-gap
grid-row-gap
grid-gap
justify-content
justify-items
align-content
align-items
grid-auto-flow

Basic Grid

  • By default all grid items will be in a single column
<div class="grid-container">
  <div class="el1">Element 1</div>
  <div class="el2">Element 2</div>
  <div class="el3">Element 3</div>
  <div class="el4">Element 4</div>
</div>

.grid-container {
  display: grid;
  margin: 1.25rem;
}
.el1 {
  background-color: orange;
}

.el2 {
  background-color: lightcoral;
}

.el3 {
  background-color: lightgreen;
}

.el4 {
  background-color: lightsteelblue;
}

Defining Columns and Rows

  • Use grid-template-columns property to set the number of columns in grid container
  • Use grid-template-rows property to explicity define rows and row height
/* 4 columns evenly spaced, one row */
.grid-container {
  display: grid;
  grid-template-columns: auto auto auto auto;
}

/* 4 columns with defined widths, 2nd and 4th column will fill unused space */
/* fr is a new unit
 * It's a unit of measurement based on a fraction of the unused space in the grid container
*/
.grid-container {
  display: grid;
  grid-template-columns: 200px 2fr 150px 1fr;
}

  • Four column grid , two rows, row 1 is 5rem tall, row 2 is 2.5rem tall
  • Rows may end up being empty if there are not a sufficient number of grid items in the grid container
.grid-container {
  display: grid;
  grid-template-columns: 200px 2fr 150px 1fr;
  grid-template-rows: 5rem 2.5rem;
}

Grid Items

  • A Grid Container contains Grid Items
  • By default, a container has one grid item for each column, in each row
  • You can however style the grid items so that they will span multiple columns and/or rows

Grid Item Properties

grid-column
grid-column-start
grid-column-end
grid-row
grid-row-start
grid-row-end
grid-area
justify-self
align-self

Grid Item Positioning

  • Use grid-column property to define on which column(s) to place an item
  • Defines where the item will start, and where the item will end
  • grid-column is shorthand grid-column-start and grid-column-end properties
  • Start Element 3 at column 3 and end at column 5
.el3 {
  grid-column: 3 / 5; /* same as  grid-column-start: 3;   grid-column-end: 5; */
  /* grid-column: 3 / span 2; same as above */
}
  • Use grid-row property to define on which rows(s) to place an item
  • Defines where the item will start, and where the item will end
  • grid-row is shorthand grid-row-start and grid-row-end properties
.el3 {
  grid-row: 1 / 3; /* same as  grid-row-start: 1;   grid-row-end: 3; */
  /* grid-row: 1 / span 2; same as above */
}

  • Set container height to specific value
.grid-container {
  display: grid;
  grid-template-columns: 200px 2fr 150px 1fr;
  grid-template-rows: 5rem 2.5rem;
  height: 500px
}
  • Use repeat() and minmax() CSS functions to size rows and columns
  • Four evenly sized colums
.grid-container {
  display: grid;
  grid-template-columns: repeat(4, 25%); /* unit can be %, em, rem, px */
  grid-template-rows: 5rem 2.5rem;
  height: 500px
}
  • Restrict row height to certain values
.grid-container {
  display: grid;
  grid-template-columns: 200px 2fr 150px 1fr;
  grid-template-rows: 5rem minmax(10px, 200px) 100px;
  height: 500px
}
  • Grid items can be made to overlap using grid-row and grid-column
.el2 {
  grid-column-start: 1;
  grid-column-end: -1;
  grid-row: 2 / span 1;
}

.el3 {
  grid-row: 1 / 3;
  grid-column: 2 / span 3;
}

Named Rows and Columns

  • Use names instead of numbers for rows and columns
.grid-container {
  display: grid;
  grid-template-columns: [col-1] 200px [col-2] fr [col-3] 150px [col-4] 1fr;
  grid-template-rows: [row-1] 5rem [row-2] minmax(10px, 200px) [row-3] 100px;
  height: 500px
}

.el3 {
  grid-row: row-1 / row-2;
  grid-column: col-2  / col-3;
}

Grid Area

  • Grid item grid-area property is a shorthand property for the
    • grid-row-start
    • grid-column-start
    • grid-row-end
    • grid-column-end properties
.el3 {
  grid-area: row-1 / col-2 / row-2 / col-3;
}

Grid Gap

  • Adjust column and/or gap size by using grid-column-gap, grid-row-gap or grid-gap
.grid-container {
  display: grid;
  grid-column-gap: 1rem;
}

grid-container {
  display: grid;
  grid-gap: 50px 100px; // row gap, column gap
}

Grid Template Areas

  • Use grid-template-areas to define areas of the grid that can be referenced by name
  • Grid with 3 rows and 4 columns
.container {
  display: grid;
  margin: 1.25rem;
  grid-template-columns: 200px 2fr 150px 1fr;
  grid-template-rows: [row-1] 5rem [row-2] minmax(10px,200px) [row-3] 100px;
  height: 500px;
  column-gap: 20px;
  grid-row-gap: 20px;
  grid-template-areas: "header header header header"
                       "side-1 main main main"
                       "footer footer footer footer";
}

/* Place element 1 in row 1, span all four columns */
.el1 {
  background-color: orange;
  grid-area: header;
}

/* Place element 2 in row 2, span 1 column */
.el2 {
  background-color: lightcoral;
  grid-area: side-1;
}

/* Place element 3 in row 2, span 3 columns */
.el3 {
  background-color: lightgreen;
  grid-area: main;
}

/* Place element 4 in row 3, span all four columns */
.el4 {
  background-color: lightsteelblue;
  grid-area: footer;
}

Grid Item Alignment

  • Use justify-content property to align the whole grid inside the container
  • Grid item total width has to be less than grid container width for justify-content to have any effect
.grid-container {
  display: grid;
  justify-content: space-evenly; // center, space-around, start, end
}
  • Use align-content property to vertically align grid items inside the container
  • Grid item total height has to be less than grid container height for align-content to have any effect

Grid Examples

12 Column Grid

<!-- HTML -->
<div class="container">
  <header>
    <h1>header</h1>
  </header>
   <nav>
     <ul>
       <li>nav item</li>
       <li>nav item</li>
       <li>nav item</li>
       <li>nav item</li>
     </ul>
   </nav>
  <main id="main-content">
    <h2>main content</h2>
  </main>
  <aside>
    <h2>sidebar</h2>
  </aside>
  <footer>
    <h2>footer</h2>
  </footer>

/* CSS */
.container > * {
  padding: 20px;
}
.container {
  display: grid;
  grid-template-columns: repeat(12,minmax(0, 1fr));
  max-width: 1200px;
  margin: 0 auto;
  color: white;
  font-family: helvetica, arial, sans-serif;
}

header {
  background: skyblue;
  grid-column: 1 / span 12;
}
main {
  background: slategray;
  grid-column: 4 / 10;
}
nav {
  background: cadetblue;
  grid-column: 1 / 4;
}
aside {
  background: seagreen;
  grid-column: 10 / 13;
}
footer {
  background: darkslateblue;
  grid-column: 1 / span 12;
}

Summary

  • Creating a Grid
    • display: grid creates a grid where child elements are automatically placed in rows
    • This default can be overwritten with grid-auto-flow, grid-auto-rows or grid-auto-columns
    • Use grid-gap to add gaps between columns and rows
  • Defining Grid Structure
    • Define columns and/or rows explicitly via grid-template-columns and grid-template-rows
    • Use repeat(times, size) to easily create columns or rows
    • Use auto-fill or auto-fit to derive the number of columns automatically
    • Use minmax() function for dynamic sizing
  • Placing Grid Items / Elements
    • Position elements in the grid via grid-row, grid-column or grid-area
    • Use span x to span a grid item over multiple columns or rows
    • Use line numbers, line names or named areas (grid-template-areas)
  • Aligning Grid Items / Elements
    • Align grid itmes via justify-items (x-axis) and align-items (Y-axis)
    • Align the entire grid content via justify-content (x-axis) and align-content (y-axis)

CSS Navigation


/* Vertical orientation */
/* HTML */
<div class="content">
  <ul class="nav">
    <li><a href="#">Home</a></li>
    <li><a href="#"> About </a></li>
    <li class="last"><a href="#"> Content </a></li>
  </ul>
</div>

/* CSS */
.nav { list-style: none; margin: 0; padding: 0; width: 200px; }
.nav li { border-bottom: 1px solid black; }
.nav li a {
  display: block; 
  padding: 0.5em;
  text-decoration: none; 
  color: black;
  background-color: lightblue;
  text-align: center;
}

.nav li a:hover { color: white; }

/* Vertical orientation */
/* Same HTML as above */

/* CSS */
.nav {
  list-style: none;
  margin:0; padding: 0;
}

.nav li { 
  float: left;
  border-right: 1px solid black;
}

/* Add class to resolve specificity problems */
.nav li.last { 
  border-right: none
}

Mobile Navigation

TBD

Responsive Design


  • Responsive design is designing a website such that it looks good on devices of various sizes and is usable in those devices
  • A web page is essentially responsive by default
    • Before any CSS is applied:
      • Block-level elements are no wider than the viewport
      • Inline elements line wrap to avoid horizontal overflow
  • As styles and elements are added, the default responsive nature of the page may break and/or the page may less visually appealing at certain viewport sizes
  • Use the following principles to implement responsive designs
    • Structure HTML for responsive design
      • Use <div class="wrapper"></div> or <main class="wrapper"></main> to enclose entire page content
      • Construct page as a series of rows <div class="row"></div> or <article> or <section>
    • Use Media queries - @media to adjust styles for different screen widths
    • Use fluid (liquid) layouts
      • Allows containers to scale to different sizes based on the width of the viewport
      • Contrast with a fixed layout where columns are defined using pixels or ems
      • Never fix the width of any container
        • Allow containers to grow naturally to 100% (minus padding and/or margin)
        • Use Flexbox for multi-column rows / sections
  • Use the viewport meta tag to instruct mobile devices to not emulate desktop browser
<head>
...
<meta name="viewport" content="width=device-width, initial-scale=1">
...
</head>

Hardware vs Software (CSS) Pixels

  • See mydevice.io for smartphone/tablet pixels vs css pixels

Media Queries

Methodology

  • Define content/HTML
  • Design wireframes
    • Desktop
    • Tablet
    • Mobile

Desktop-First Design

  • Write styles for desktop display
  • Use browser dev tools to determine breakpoints for tablet and mobile view
  • Adjust styles for tablet and mobile display by writing max-width media queries
  • Styles that apply to desktop display should be outside of any media queries
/* styles for desktop display are outside of any media queries */
/* Note that the order of the media queries matters - max-width must decrease */
...

@media (max-width: 768px) { 
  /* styles for tablet display */
  /* start with this width and adjust as necessary */
  /* viewport width can be no greater than 768px for the style(s) to apply
   * If greater than this, style(s) won't apply 
   */   
}
@media (max-width: 400px) {      
  /* styles for mobile display */
  /* start with this width and adjust as necessary */
  /* viewport width can be no greater than 400px for the style(s) to apply
   * If greater than this, style(s) won't apply 
   */   
}

Mobile-First Design

  • Write styles for mobile display
  • Use browser dev tools to determine breakpoints for tablet and desktop view
  • Adjust styles for tablet and desktop display by writing min-width media queries
  • Styles that apply to mobile display should be outside of any media queries
/* styles for mobile display are outside of any media queries */
/* Note that the order of the media queries matters - min-width must increase */
...

@media (min-width: 768px) { 
  /* styles for tablet display */
  /* start with this width and adjust as necessary */
  /* viewport width must be at least 768px for the style(s) to apply
   * If less than this, style(s) won't apply 
   */   
}
@media (min-width: 1024px) {      
  /* styles for destop display */
  /* start with this width and adjust as necessary */
  /* viewport width must be at least 1024px for the style(s) to apply
   * If less than this, style(s) won't apply 
   */   
}

Bootstrap Responsive Breakpoints

  • Bootstrap implements a Mobile-First design philosophy for breakpoints
// Extra small devices (portrait phones, less than 576px)
// No media query for `xs` since this is the default in Bootstrap

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }

Responsive Images

/* Mobile style */
.hero {
  ...
  background-image: url(image-small.jpg);
  ...
}

/* Tablet style */
/* viewport width has to be at least 35rem (560px) for the style(s) to apply
 * If less than this, style(s) won't apply and mobile style(s) will apply. 
 */                                      
@media (min-width: 35rem) {                               
  .hero {                                                
    ...                                                                   
    background-image: url(image-medium.jpg);
    ...                                                    
  }                                                      
}                                                        
                                                         
/* Desktop style */
/* viewport width has to be at least 50rem (800px) for the style(s) to apply
 * If less than this, style(s) won't apply and either mobile or tablet style(s) will
 * apply.
 */                                         
@media (min-width: 50rem) {                               
  .hero {                                                
    ...                                                                   
    background-image: url(image.jpg);
    ...                                                    
  }                                                      
}                                                               
  • For images added with <img> tag use the srcset HTML attribute
<img alt="A white coffee mug on a bed of coffee beans"
     src="image-small.jpg"             
     srcset="image-small.jpg 560w,       
             image-medium.jpg 800w,
             image.jpg 1280w"
/>
  • Always specify img { max-width: 100%; } to ensure images don't overflow their container.

Responsive Video

Responsive Tables

CSS Transforms - Transforming Elements

  • Use the following CSS properties to rotate, scale, move and perform 3D transformations on elements
  • transform()
  • transform-origin
  • Rotate and move (translate) element
selector {
  ...
  transform: rotateZ(45deg) translateX(3.5rem) translateY(-1rem);
  transform-origin: center;
  ...
}

Modular CSS


Media Object Pattern

<div class="media">
  <img class="media-image" src="image.png">
  <div class="media-body">
    <h4>This is an image </h4>
    <p>More information about the image</p>
  </div>
</div>

Sass


  • Sass
  • SassMeister
  • Sass - Syntactically Awesome Stylesheets
  • Scss - Sassy CSS

Install sass

  • NOTE: node-sass is deprecated. Use sass instead
# Install sass globally
npm uninstall -g node-sass
npm install -g sass

Sass Features

  • Variables
  • Selector Nesting (Nested Rules)
  • Partials and Import
  • Mixins
    • A Mixin is a fragment of Sass that can easily be applied to another selector
    • It's a portable set of css properties/values
  • Functions
  • Extend/Inheritance

Using Sass

# Compile a single file to CSS 
sass style.scss style.css

# Add the --watch flag to tell Sass to automatically recompile the file on change
sass --watch style.scss style.css

# Tell Sass to watch a folder
sass --watch scss:css

# Tell Sass to watch multiple folders
sass --watch sass/ sass/components/ --output css/ --source-map true --source-map-contents sass

Accessibility


  • ARIA

Canvas


JavaScript Libraries


JavaScript Polyfills

  • Whenever there is some HTML or CSS that's not supported across all browsers and/or versions there is usually a Polyfill available to add support

IE Polyfills

  • HTML5shiv is a Javscript workaround to provide support for the new HTML5 elements in IE 6-8
  • Respond.js is a fast polyfill for min/max-width CSS3 Media Queries for IE 6-8
<head>
...
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
...
<!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
...
</head>

Other Polyfills

Automation Tools


  • Grunt
  • Gulp

Performance


Tools


  • Use MAC built in screen capture tool to measure width and height of elements, margins, spacing etc.
    • Cmd-Shift-3 - take screen-shot of entire screen and copy .png to Desktop
    • Cmd-Shift-4 - select and copy to Desktop
    • Cmd-Ctl-Shift-4 - select and copy to Clipboard
  • Use MAC SIP color-picker tool to select colors on mockup and convert to hex code.
  • Use Whats My Font Chrome extension to identify fonts
  • Use FireShot Chrome extension for screenshots

Device Screen Resolution

Emmet

Workflow (in Progress)


  • General Notes
    • Rely on Google search to help resolve issues
  • Designer Deliverables
    • Full page mockups (set of PhotoShop or PDF documents)
    • Page(s) with typography examples - headings, paragraphs etc.
    • Page(s) with UI elements - links, buttons etc.
    • Color palette
  • Review Mockup
    • When looking at a mockup, go through the exercise of putting boxes around sections of the mockup - this is a good way to visualize the various elements that will be needed.
    • Try to break down the boxes into their smallest component
    • This is called an atomic or component based approach
  • Write HTML (with no styling)
  • Create sass/ and sass/components/ directory
  • Create styles.scss and Sass partials (_base.scss, _variables.scss, _functions.scss etc)
  • Review color palette and assign colors to variables.
  • Style Layout (pass #1)
  • Start at top of page (header) and work down
  • Style topography, colors, spacing
  • For each component:
    • Identify header(s)
    • Style headers with font and typography that matches design mockup
    • Use screen capture tool for measurement and SIP for color matching
    • Use SMACSS style class names for styling
  • For each component:
    • Style remaining text (paragraphs etc.) - concentrating on typography

CSS Review Questions


Q1  What are different ways to apply styles to a Web Page?
A1  
Inline CSS:  <p style="color;red; font-size:1em"> Line 1 </p>
Embedded CSS: (In HTML document)  with <style> tag
External style sheet: 
<link rel="stylesheet" href="css/style.css"> 
@import url('css/style.css')

Q2  How does CSS precedence/cascading work?
A2  Cascade is how CSS resolves conflicts between styles precedence inline, embedded, global
    (most specific rule wins!)
    Specificity is a numerical value assign4ed to a selector

Q3  What is a selector, class selector, ID selector?
A3  A selector is the part of a CSS rule that identifies which element to style
    Class is an HTML element attribute that can be used as a CSS selector or for Dom scripting.
    Multiple HTML elements can have the same class attribute.
    ID is an HTML attribute like class but id must be unique, no two elements can have same id

Q4  What is doctype?
A4  Basically tells browser how to interpret a document <doctype html>

Q5  What does CSS reset file do?
A5  Resets all margins, padding etc to 0, normalize sets up reasonable defaults

Q6  Describe Floats?
A6  Floats are used to position elements horizontally
    Allows text to float around floated element
    Also used for columnar layout
    Used to clear on subsequent element to position it in normal flow

Q7  Z-index is used to control stacking of overlapping elements

Q8  Hide Content 
    display:none:inline:block <-- element & space disappears
    visibility:hidden:visible <-- leaves space where element would have been

Q9  Box Model explanation, box-sizing property

Q10 Difference between inline and inline-block?
    inline-block can have margin, height/widht applied to it

Q11 Responsive Design
   - Design site such that it adapts to device screen size
   - Change all widths, margins and padding to percentages
   - Change font-sizes to rem or em
   - Use media queries to change layout/styling at appropriate widths
   - Scalable images

Q12 Difference between position: relative, absolute, fixed

Q13 Selectors
    - Universal, element, id, class, descendant, grouped, pseudo-class, pseudo-element, 
    child, general sibling, attribute

Q14 Conditional Inclusion
     <!-- [if IE 6]>
       <link href=".....">
     <! [endif]-->

Q15 How do you achieve a two/three column layout?
A15 Floats, Flexbox, CSS Grid 
⚠️ **GitHub.com Fallback** ⚠️