HTML and CSS CheatSheet

HTML IntroductionGo to video for this category

Ref: MDN_Guides:HTML | W3schools:HTML

Syntax and style guidelines:

Ref: Google:HTML-CSS Style Guide
  • Use lower case letters for tags, attributes, id names, class names. 
    • Separate words with hyphens.
  • Choose id and class names that reflect the purpose of the element, or that are generic. Names should be as short as possible but as long as necessary.
  • Use double quotes for attributes: <img src="pic.png" alt="some pic">
  • Indent 2 spaces. Don't use tabs.
  • Use <hr> instead of <hr /> syntax for empty elements.
  • Comments: <!-- This is a comment -->

HTML Elements

Definitions
  • HTML (Hypertext Markup Language): Defines the semantic structure of a web page document. 
    • "Hypertext" refers to clickable links that connect web pages to one another, either within a single website or between websites. 
    • "Markup" annotates text, images, and other content for display in a Web browser.
  • HTML5: The 5th and latest generation of HTML. It added numerous elements and functionality. The first draft was released in 2008, and was released as an official W3 Recommendation in Oct 2014. Most of its functionality was incorporated in browsers around 2012. It is not supported in IE8 or earlier.
  • Tags: HTML consists of elements marked by tags. Tags are surrounded by angle brackets. Examples of tags: <html>, <h1>, <p>, </h2>.
  • Elements: Everything from the start tag to the end tag. <p>This is a paragraph element</p>
  • Nested elements: Elements within other elements
  • Empty elements: Elements that are self contained and only have one tag. Most commonly used empty elements: br, hr, img, input, link, meta.
  • Attributes: Information about an element. Put in the opening tag in quotation marks. Double quotation marks are the convention but single quotes also work. Multiple attributes in the same element are separated by spaces.
    • Name-value pairs: Attributes come in name-value pairs formatted as name="value"

Attributes

Ref: MDN:Attribute_list 
Ex: <input type="submit" class="btn btn-primary" value="Save">
Global Attributes can be applied to any element
  • id Defines a unique identifier for an element. Should be unique in the whole document.
  • class Specifies one or more classnames to apply to that element and it's descendants.
  • style Apply inline styles directly to an element. Generally styles should be in a separate stylesheet.
  • data-*  Create your own custom attribute by replacing the * with relevant word(s). Ref: MDN:data Ex: <div data-article-category="tech">Learn HTML</div>
Boolean Attributes
If a boolean attribute is present, its value is true. The default value is false, so if it is not present, it is false. <tag attributeName>
Example
<input name="title" required autofocus> 
  • The required attribute makes this input field required.
  • The autofocus attribute automatically focuses the cursor on this input element.
Onevent Attributes
You can use onevent attributes to execute JavaScript code.
Common examples: onclick, onhover, onfocus, onblur, onsubmit, onload. 
Full list: MDN:GlobalEventHandlers
<button onclick="alert('Button clicked')">Click Me</button> When clicked, an alert is triggered.
Onevent attributes are generally not recommended to keep JS separate from HTML.
Preferred: Add an id attribute and place an event listener in a separate JS file.
<button id="alert-button">Click me</button>
<script> <!-- ideally this script would be in a separate JS file -->
  const button = document.getElementById('alert-button');
  function displayAlert() { alert('Button clicked') }
  button.addEventListener('click', displayAlert);
</script>

HTML Page Template

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="INSERT DESCRIPTION HERE">
  <meta name="author" content="YOUR NAME HERE">
  <title>Page title here</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <!-- content here -->
</body>
</html>
Element info
  • <!DOCTYPE html> Tells the browser this is an HTML5 webpage. Old browsers that do not support HTML5 will revert to HTML 4.
  • <html lang="en-US"> The root element of the HTML document. Set the lang attribute so that screen readers can announce the proper language.
  • <head> Contains meta information about the document and is not displayed by the browser.
  • <meta charset="UTF-8"> Tells the browser to use UTF-8 as the character encoding. UTF-8 is the dominant character set on the web and is able to display all languages consistently.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0"> The browser's viewport is the area of the window in which web content can be seen. Set this attribute for mobile browsers. Ref: MDN: Viewport_meta_tag
  • <meta name="description" content=""> Provide a brief summary of the web page content. Displayed as part of search engine results snippet. Google will cut off more than 158 characters (including spaces). Mobile devices cut off after 120 chars.
  • <title> Sets the title of the page. It is displayed on the browser tab, and as the bookmark title if the user bookmarks the page. It is also displayed in search engine results. Should be concise and informative. 
  • <link rel="stylesheet" href="style.css"> Link to an external stylesheet. Add the absolute or relative path to the stylesheet in the href attribute. The type attribute is not needed.
  • <body> Contains the content you want to display. Use this element for styles you want to apply across the whole page.

Generate HTML document in VS Code: !+tab

LayoutGo to video for this category

Ref: MDN:Document_and_website_structure

Layout Semantic Elements

Ref: MDN:Elements (Content Sectioning)
Use semantic tags to structure the HTML document. Each is a block element:
  • <header> Introductory content or navigational aids. May include a navigation bar, company logo, page heading.
  • <nav> Navigation bar.
  • <aside> Portion of a document whose content is only indirectly related to the document's main content. Asides are frequently presented as sidebars or call-out boxes.
  • <main> The dominant content of the document. Directly relates to the main topic or function of the document or website.
  • <h1> thru < h6> Different levels of section headings.
  • <p> Paragraph.
  • <section> A standalone section.
  • <article> Block of content that makes sense on its own (such as a blog post).
  • <address> For contact information (address, phone, email, website, etc.).
  • <figure> Use these tags around an image tag. Especially useful when combined with figcaption.
  • <figcaption> Put inside the figure tags and after the image tag to include a caption with your image.
  • <footer> footer content.
Default CSS
header, nav, aside, main, section, article, figure, footer { display: block }
address { display: block;  font-style: italic; }
figure { display: block; margin: 1em 40px; }

Navbar

Basic navbar elements and style:
  • Nav: Set background color, padding and bottom margin. 
  • Container div: set left and right margin.
  • Unordered list: Remove the bullet-points and spacing.
  • List items: Change display from block to inline.
  • Anchor tags: Link to site pages relative to site root path. 
Set display to inline-block. Set color, padding, remove underline. 
  • Brand/site name: Place first. Set font-size, color, right margin.
Example
Basic Navbar:
<nav class="navbar">
  <div class="container">
    <ul>
      <li><a class="navbar-brand" href="#">Site Name</a></li>
      <li><a href="/path1">Page-1</a></li>
      <li><a href="/path2">Page-2</a></li>
      <li><a href="/path3">Page-3</a></li>
    </ul>
  </div>
</nav>
CSS:
  • Layout: horizontal across the top of the screen.
  • Color: black background with white brand and grey links
body { margin: 0 }
.container { margin: 0 1rem; }
.navbar {
  background-color: black;
  margin-bottom: 2rem;
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
}
.navbar ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
.navbar li {
  display: inline;
}
.navbar a {
  color: lightgrey;  
  text-decoration: none;
  display: inline-block;
  padding: 8px;
}
.navbar-brand {
  color: white!important;
  font-size: 1.2rem;
  margin-right: 1rem;
}
  • Hover: Change link appearance on hover: a:hover { /* style declaration */ }
  • Active: Add an "active" class to a link to change its color/background-color.
  • Align link to right: Set float property to "right" on the li element.
  • Stick navbar to top when scrolling: nav {position: sticky; top: 0;}
Examples
  • Change link color on hover:
.navbar a:hover { color: slateGrey; }

  • Add an active class to a link changing the background color and box corners of the link:
<li><a class="active" href="/path1">Page-1</a></li>
Stylesheet:
.active {
  background-color: slateGrey;
  border-radius: .25rem;
}

  • Align nav link to the right:
<li class="float-right"><a href="/path3">Page-3</a></li>
Stylesheet:
.float-right { float: right; }

  • Make the navbar stick to the top when scrolling: 
.navbar {
  position: sticky;
  top: 0;
}

CSS

Body element: To set style rules for the entire document, set them in the body element.
Set margin to 0, line-height to somewhere between 1.5 and 2, font-family stack, color and background-color if you don't want the black/white default.

Html (i.e., root) element: Use the html element if you want to change the base font-size, or to use the border-box width settings.
Container class: Create a container class to set padding for your site's content. 
Example html, body, .container style rules
  • Rem units are in reference to the root element which is html. So if you want to change the font-size from the browser default of 16px, do so on that element. For accessibility reasons use rem units because users can't change the base font size if it's set in px.
  • If you want to set box-sizing to border-box so that the width property will include any border and padding, do so in the html element, then inherit it on the * universal element.
html {
  box-sizing: border-box;
  font-size: .875rem; /* sets base font to 14px (14px ÷ 16px = .875) */
}
*, *::before, *::after {
  box-sizing: inherit;
}
body {
  margin: 0;
  font-family: system-ui, Helvetica, Arial, sans-serif;
  line-height: 1.5;
  color: #212529; /* Grey-black, Bootstrap's text color */
  background-color: #f5f5f5; /* White-smoke */
}
.container {
  margin-right: 1rem;
  margin-left: 1rem;
}
  

Media Queries

Ref: MDN: Using_media_queries
Set different style rules depending on user device characteristics.
@media (min-width: __px) { /* style rules */ } If width is at least __px, apply style rules.
@media (max-width: __px) { /* style rules */ } If width is __px or smaller, apply style rules.
@media print { /* style rules */ } When printing, apply style rule.
Example: remove element on smaller screen
<img src="pic.jpg" alt="" class="d-sm-none">
Remove the image by setting display to none when screen width is 768px or smaller:
@media (max-width: 768px) {
  .d-sm-none { display: none }
}

Alternatively: 
<img src="pic.jpg" alt="" class="d-none d-md-inline">
Set display to none. Use media query to check if screen width is 768px or larger. If so, apply class .d-md-inline which will set display property to inline (the default for images).
.d-none { display: none; }
@media (min-width: 768px) {
  .d-md-inline { display: inline }
}

Bootstrap 

Container: getbootstrap.com/docs > click Layout: Containers
Navbars: getbootstrap.com/docs > click Components: Navbar

TextGo to video for this category

Ref: MDN:HTML Elements (then select element)

Block Elements

Elements with style display: block generate line breaks before and after the element.

Headings: h1-h6
Ex: <h1>Articles</h1>
Default CSS
h1, h2, h3, h4, h5, h6 { display: block; font-weight: bold; }
h1 { font-size: 2em; margin: .67em 0px; }
h2 { font-size: 1.5em; margin: .83em 0px; }
h3 { font-size: 1.17em; margin: 1em 0px; }
h4 { font-size: 1em; margin: 1.33em 0px; }
h5 { font-size: .83em; margin: 1.67em 0px; }
h6 { font-size: .67em; margin: 2.33em 0px; }
Group headings:
<hgroup>
  <h1>Learn HTML</h1>
  <h2>by Joey R.</h2>
</hgroup>
Other Text-related block elements
  • <div> A generic container for content division. 
  • <p> paragraph.
  • <pre> Preformatted text, displayed exactly as written including spaces and line breaks.
  • <blockquote> Extended quotation. 
    • <cite> Inline element to site the source within the blockquote.
  • <hr> Horizontal rule (line) used to visually separate content.
Default CSS
All (except cite) include { display: block; } in addition to:
div { margin: 0px }
p { margin: 1em 0px; }
pre { font-family: monospace; white-space: pre; margin: 1em 0px; }
blockquote { margin: 1em 40px; }
  cite { display: inline; font-style: italic; }
hr { margin: 0.5em auto; border-style: inset; border-width: 1px; }
  • All these elements except div (and cite) have top and bottom margin.
  • Cite is not a block element. It's only listed here because it goes together with blockquote.

Inline Elements

Element box style display: inline 
Width and height properties do not affect inline elements
  • <span> A generic inline container. 
  • <b><strong> Displayed as bold. 
    • <b> Bold. Used to draw the reader's attention to the content w/o implying special importance.
    • <strong> Screen reader: indicate strong importance, seriousness, or urgency.
  • <i><em> Displayed as italic.
    • <i> Italic. Used to distinguish the content from the surrounding element for some reason.
    • <em> Screen reader: stress/emphasize the content.
  • <u> Underline. Indicates some non-textual annotation (e.g., this is a hyperlink).
  • <s> Strike-through.
  • <sup> Superscript. Used solely for typographical reasons.
  • <sub> Subscript. Used solely for typographical reasons.
  • <mark> Mark or highlight text. Applies a yellow background.
  • <code> Short fragment of computer code.
  • <kbd> Keyboard. Indicates user input from a keyboard, voice input, etc.
  • <samp> Computer output.
  • <small> Renders text one font-size smaller than the parent element. Used to present side comments or small print.
  • <br> Inserts a line break.
Default CSS
span { }
  • Use span to apply separate styles to the content or because the content shares attribute values.
  • Span has no default style rules.
b, strong { font-weight: bold; }
  • To display text as bold just for presentational purposes, without implying importance or special attention, you can apply style font-weight: bold to whatever element the content is already in.
i, em { font-style: italic; }
u { text-decoration: underline; }
  • The u element should not be used merely for presentational purposes. In that case you can apply style text-decoration: underline to whatever element it is in.
s { text-decoration: line-through; }
  • Don't use the s element for indicating document edits. Use <del> and <ins> elements instead.
sup { vertical-align: super; font-size: smaller; }
sub { vertical-align: sub; font-size: smaller; }
code, kbd { font-family: monospace; }
small { font-size: smaller; }

Special Characters / HTML Entitities

Useful HTML entities including for escaping HTML and SQL code:
&nbsp; space (non-breaking space)
&lt;  < less than
&gt;  > greater than
&amp;  & ampersand
&quot; " double quote
&apos; ' single quote or apostrophe
&sol; / forward slash
Generally use actual UTF-8 characters rather than HTML entities:
• bullet point (alt+8 on Mac), ¢ cent, € euro, £ pound, ¥ yen, § section, © copyright, ® registered trademark, ™ trademark, — long dash
File tree: app-name/
├── package.json
└── index.html

CSS

Ref: MDN_Guides:Styling_text 

Use body element to set style rules for the entire document: body { color: navy; }

Styling Fonts

Color
color: #000000; Sets text color. Browser default is black. 
color: #212529; Bootstrap uses a greyish black.
Font properties: font-size, font-family, font-weight, font-style, font-variant.

Font Size
Base font size: (Browser default is 16px).
  • Rem units are based on the root font-size set on the html element.
  • html { font-size: .875em; } Sets the base font-size to 14px (i.e., 16px * .875).
For other elements use relative font-sizes: rem, em.
  • .small-print { font-size: .8rem }
larger, smaller keywords: Change font size relative to the parent element's font size:
  • .large-print { font-size: larger } parent's font size * 1.2
  • .small-print { font-size: smaller } parent's font size / 1.2
Accesibility, absolute-size keywords
  • Accessibility: Users with limited eyesite may change their browser's base font size so always use relative font-sizes instead of absolute.
  • Absolute-size keywords: xx-small, x-small, small, medium, large, x-large, xx-large, xxx-large are not accesible, meaning if the user changes the default font-size they will not adjust accordingly. So preferrable to use rem, em or percentages.
  • Formula to convert from pixel to em: px/font-size=em. Ex: 14/16=.875
Font Family
Some common web safe font stacks (with more at w3schools.com)
font-family: Helvetica, Arial, sans-serif;
font-family: "Trebuchet MS", Verdana, sans-serif;
font-family: Geneva, Tahoma, sans-serif;
font-family: "Times New Roman", Times, serif;
font-family: Georgia, serif;
font-family: "Courier New", Courier, monospace;
Font stacks, web safe fonts, generic font families
  • Each browser uses a default font-family which is in turn displayed differently on different operating systems. Setting a font stack ensures a more consistent look across devices.
    • The default font used in the major browsers is Times or Times New Roman. The default san serif font used by browsers is Arial or Helvetica.
  • Put multi-word fonts in quotes: "Times New Roman"

Font stack:
  • When you set a font-family value, the browser can only apply it if it's available on the user's machine. If not it will apply the browser default font. 
  • For that reason it's advisable to provide a stack of multiple fonts (commonly 3) as a fallback system. List your preferred font families first, in order of preference. List the generic font (e.g., sans-serif, serif, or monospace) last. If the browser does not support the first font, it tries the next one.
  • Bootstrap font stack: font-family: "Helvetica Neue", Helvetica, Arial, sans-serif.

Web safe fonts:
 Ref: Wikipedia.org/wiki/Web_typography
  • Web safe fonts are available on essentially all major operating systems (Windows, macOS, most common Linux distributions, Android, iOS).

Generic font families:
  • There are five generic font families that all browsers have as a fallback. The first three are similar across all browsers but the last two are less predictable:
  • Serif: Uses tails on the ends of letters. Common for content in print newspapers and magazines. Older computer monitors with low PPI (pixels per inch) density make serifs look blurry.
    • Note: MS Word used the Times New Roman serif font until 2007 when it was replaced with the Calibri sans-serif font.
  • Sans-serif: Does not use tails on the ends of letters. Most websites use sans-serif fonts as they are more readable on monitors with low PPI density (96 PPI is common in older monitors).
  • Monospace: Every character is the same width. Commonly used to display computer code.
  • Cursive: Meant to emulate handwriting.
  • Fantasy: Intended to be decorative.
System UI font:
  • Uses the device's system font, giving the site a more native feel. Universal browser support from 2021.
  • For older browsers list the device's operating system font: -apple-system for MacOS and iOS, "Segoe UI" for Windows 10, "Segoe UI Variable" for Windows 11, Roboto for Android.
Example
Example font stack order:
  1. System-ui as the first choice. 
  2. For browsers not supporting system-ui use the apple, MS, and Android system font name.
  3. List web-safe font families Helvetica or "Helvetica Neue" (for Mac) and Arial.
  4. Lastly, list the generic sans-serif font.
body {
  font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif
}
Google Fonts: fonts.google.com
Find a font, add the link in the head element:
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=FONT-NAME">
Add it to your stylesheet: body { font-family: FONT-NAME, other fonts }
Font-weight, font-style, text-decoration, text-transform, font-variant, text-shadow
  • font-weight: bold; To unbold set value to normal.
  • font-weight: 100-900; 100 is lightest, 900 darkest. 400 is normal, 700 is bold.
  • font-style: italic; To remove italics set value to normal.
  • text-decoration: underline; To remove underline (e.g., from a link) set value to none
    • overline Puts a line above the text. 
    • line-through Puts a line through the text (a strike-through). 
  • text-transform: uppercase Transforms the text to all upper case 
    • lowercase Transforms the text to all lower case.
    • capitalize Capitalizes the first letter of each word. 
  • font-variant: small-caps; To remove small caps set value to normal.
  • text-shadow: 1px 1px 1px red, 2px 2px 1px red; Ref: MDN:text-shadow

Text Layout

Alignment
  • text-align: center; Values: start/left, center, end/right, justify (all lines the same width).

Line height, text-indent
  • line-height: 1.5; A multiple of the element's font-size. Default value is normal which usually results in 1.2 but can vary by font-family. For accessibility, recommended line height is 1.5 to 2.0 (double space). Bootstrap uses 1.5.
  • text-indent: 3rem; Indentation of first line in a block. Use length or percentage values. Values can be negative. Default: 0px.
Letter-spacing, word-spacing
  • letter-spacing: -1px; Change letter spacing relative to normal.
  • word-spacing: 1px; Change space between words and tags relative to normal. 
Details
  • Default value: normal is set by the current font and browser. 
  • Generally use px, em or rem units. 
  • Values are relative to normal so 0px/0em/0rem are no change. 
    • Positive values increase the width from normal. Ex: 1px, .1em, .1rem.
    • Negative values decrease the width from normal. Ex: -1px, -.1em, -.1rem. 
White space, new lines and wrapping
  • white-space: normal; White space collapsed. Newline characters ignored. Lines wrap.
    • nowrap White space collapsed. Newline characters ignored. Lines don't wrap.
    • pre White space preserved. Newline characters recognized. Lines don't wrap.
    • pre-wrap White space preserved. Newline characters recognized. Lines wrap.
    • pre-line White space collapsed. Newline characters recognized. Lines wrap.
  • overflow-wrap: normal; Words with more characters than the total row will not wrap.
    • break-word Words with more characters than the total row will break to a new line.
White space collapsed, newline characters, non-wrapping lines
  • White space collapsed: More than one space is ignored. Tabs or spaces before the content are ignored. Trailing spaces ignored.
  • Newline characters: If the HTML is on a new line it will be displayed on a new line. Simply pressing the return key when entering the text will put it on a new line.
  • Non-wrapping lines: Extend off the screen to the right if line width exceeds screen width. The browser will add a horizontal scrollbar. Non-wrapping lines can still be broken with the <br> tag, and with newline characters if recognized (i.e., with whitespace: pre).

Bootstrap - Typography

Ref: getbootstrap.com/docs > click Content: typography | Utilities: text
Text align: text-start text-center text-end
Text wrap: text-wrap text-nowrap
Text transform: text-lowercase text-uppercase text-capitalize
Bold (font-weight): fw-normal fw-bold fw-bolder fw-semibold fw-light fw-lighter
Italic (font-style): fst-normal fst-italic
Underline (text-decoration): text-decoration-none text-decoration-underline
Strike-through (text-decoration): text-decoration-line-through
Monospace: font-monospace
Font size: (note: vw is percent of the viewport width)
.fs-1 calc(1.375rem + 1.5vw) | 22px + 1.5vw
.fs-2 calc(1.325rem + .9vw) | 21.2px + .9vw
.fs-3 calc(1.3rem + .6vw)  | 20.8px + .6vw
.fs-4 calc(1.275rem + .3vw) | 20.4px + .3vw
.fs-5 1.25rem!important; | 20px
.fs-6 1rem!important; | 16px
Line height: (line height above 1 adds space between lines relative to font size)
lh-1 (same as the line's font size, i.e., no space between lines)
lh-sm (1.25 times the font size, i.e., small space between lines)
lh-base (1.5 times the font size, i.e., space between lines is 50% of font size)
lh-lg (2 times the line's font size, i.e., double-space)

ListsGo to video for this category

Ref: MDN:ul
Note: you can nest a list within a list.

Unordered List

<ul>
 <li>List item 1</li>
 <li>List item 2</li>
</ul>

Ordered list

<ol>
 <li>List item 1</li>
 <li>List item 2</li>
</ol>     
Type attribute, start attribute, reversed attribute.
type attribute: Default: "1" (i.e., numbers)
  • <ol type="A"> Capital Letters
  • <ol type="a"> Lowercase letters
  • <ol type="I"> Roman numerals upper case
  • <ol type="i"> Roman numerals lower case
start attribute: Default: "1"
  • <ol start="5"> starts the list at 5. 
reversed attribute: reverses order
  • <ol reversed>

Description List

<dl>
  <dt>Term 1</dt>
  <dd>Definition for term 1.</dd>
  <dt>Term 2</dt>
  <dd>Definition for term 2.</dd>
</dl>
Details
  • Description list elements enclose a list of terms and their definitions. 
  • Examples: Glossary, metadata.

CSS

Unordered List  

Default CSS
ul {
  display: block;
  list-style-type: disc; /* other options: circle, square, none */
  list-style-position: outside; 
  margin-top: 1em;
  margin-bottom: 1em;
  margin-left: 0;
  margin-right: 0;
  padding-left: 40px;
}
  • list-style-position: inside means the marker is inside the list item. Outside means it's outside the list item.
  • Remove indentation: 
<ul style="list-style-position: inside; padding-left: 0px;">
  • Remove marker and indentation: 
<ul style="list-style-type: none; padding-left: 0px;">
list-style-position
list-style-position property values:
  • Outside (default): if an li element is longer than one line, the second line indents the same as the first line.
  • Inside: if an li element is longer than one line, the second line does not indent.

Ordered List

Default CSS
ol {
  display: block;
  list-style-type: decimal; /* upper-alpha, lower-alpha, upper-roman, lower-roman, none */
  list-style-position: outside;
  margin-top: 1em;
  margin-bottom: 1em;
  margin-left: 0;
  margin-right: 0;
  padding-left: 40px;
}
  • list-style-position: inside means the marker is inside the list item. Outside means it's outside the list item.
  • Remove indentation: 
<ol style="list-style-position: inside; padding-left: 0px;">

Description List 

Default CSS
dl {
  display: block;
  margin-top: 1em;
  margin-bottom: 1em;
  margin-left: 0;
  margin-right: 0;
}

Bootstrap - List Groups

Ref: getbootstrap.com/docs/5.2/components/list-group
<ul class="list-group">
  <li class="list-group-item">An item</li>
  <li class="list-group-item">A second item</li>
</ul>
  • list-group list-group-flush Alternative format
  • list-group list-group-numbered Numbered list
Numbered Example
<ol class="list-group list-group-numbered">
  <li class="list-group-item">Item 1</li>
  <li class="list-group-item">Item 2</li>
</ol>

TablesGo to video for this category

Ref: MDN:table
Basic Table
<table>
  <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>
</table>
Details
  • <table> </table> Tags to create a table.
  • <tr>row text or format in a table</tr>  Table rows that will contain cells.
  • <td>cell data</td> Contains the table data. The text is regular and left-aligned. A tag can contain text, links, images, lists, forms, other tables, etc.
Table with caption, headers, footer
<table>
  <caption>Articles</caption>
  <thead>
    <tr><th>#</th><th>Title</th><th>Author</th></tr>
  </thead>
  <tbody>
    <tr><td>1</td><td>Learn HTML</td><td>Joey R</td></tr>
    <tr><td>2</td><td>Learn CSS</td><td>Sheena R</td></tr>    
  </tbody>
  <tfoot>
    <tr><td colspan="3">Footer text</td></tr>
  </tfoot>
</table>
Details
  • <caption> Optional Table Caption. The caption will always be on top and outside the borders.
  • <thead> Optional tag that groups the header content in the table.
  • <th>header text</th> Contains header information. The text is bold and centered.
  • <tbody> Optional tag that groups the body content in the table.
  • <tfoot> Optional tag that groups the footer content in the table (if any).
  • To put the headers down the left column, put <th> tags right after each new row <tr> tag.
  • <td colspan="3">cell data</td> You can make a cell that spans multiple columns with the colspan attribute.
  • <th rowspan="2">cell data</th> Or that spans multiple rows.

CSS

Ref: MDN Guides:Styling_tables

Borders:
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}

Width and height:
table { width: 100%; } Set table width to whole page.
th, td { height: 20px; } Set cell height
table { table-layout: fixed; width: 100%; } Set all columns to equal width.

Alignment:
th { text-align: left; } Set horizontal alignment: left, center, right.
td { vertical-align: bottom } Set vertical alignment: top, middle, bottom.
Padding: td, th { padding:10px; }
Color: 
th { background-color: black; color: white; } Header black with white letters.
Color every other row: 
Add class to every other row <tr class="color-row">
CSS: tr.color-row td {background-color: LightGray}

Bootstrap

Ref: getbootstrap.com/docs > click Content: Tables
  • table Basic table class
  • To color the whole table, or individual rows or cells apply class:
    table-light table-dark table-primary table-secondary  table-success  table-warning  table-danger  table-info
  • table-striped adds grey background to every other row.
  • table-striped-columns adds grey background to every other column.
  • table-hover adds grey background to row on hover.
  • table-active adds grey background to the row or cell the class is applied to.
  • table-bordered adds borders around each cell.
  • table-borderless removes all borders on the table.
  • table-sm makes the table smaller by cutting the cell padding in half.
Example
<table class="table table-dark table-sm table-hover">
  <thead>
    <tr>
      <th>Col 1 Heading</th>
      <th>Col 2 Heading</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Row 1 Column 1</td>
      <td>R1 C2</td>
    </tr>
    <tr >
      <td>Row 2 Column 1</td>
      <td>R2 C2</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Bottom Row C1</td>
      <td>Bottom Row C2</td>
    </tr>
  </tfoot>
  <caption>Optional Table Caption Here.</caption> 
</table>

FormsGo to video for this category

Ref: MDN:form

Basic Form:

<form action="" method="POST">
  <div>
    <label for="title">Title</label>
    <input type="text" id="title" name="title">
  </div>
  <button type="submit">Save</button>
  <button type="reset">Reset</button>
  <a href="/path/back">Cancel</a>
</form>
Form element explanations
  • Form element:
    • Action attribute: URL that the form is submitted to. Blank will submit to the same URL as the form. 
    • Method is the HTTP request method the form is submitted with. 
      • Method can only be POST or GET when sent from a web browser. Non-browser forms (e.g., mobile apps) can additionally use the PUT, PATCH, and DELETE methods. 
      • POST requests send the submitted form data in the body of the request message. Use the POST method for forms unless there is a specific reason to use a GET request.
      • GET requests send the form data in the URL as a query string. Use the GET method when there is a reason to show the form data in the URL. For instance search forms generally use the GET method so the user can see the search string and even save the URL with the search string. 
  • Label element: the "for" attribute value is the field id. Clicking on the label gives the same response as clicking in the form field.
  • Form fields can be input, textarea, or select elements.
  • <fieldset>...</fieldset> Creates a border around a form field or fields.
    • <legend>Fieldset label</legend> Placed just below the opening fieldset tag inserts a label in the fieldset border.
  • Form elements must contain an input or button element of type="submit". The form is submitted when it is clicked.
  • Optionally include a reset button to clear the form data.
  • A "Cancel" link with a path back to the relevant page.

Form Fields

Input Element
  • The input element is the most frequently used form field element. Changing the type changes the values allowed:
  • Text Input: 
<label for="title">Title</label>
<input type="text" id="title" name="title" maxlength="200" required>
  • Email Input: Must be in email format
<label for="email">Email</label>
<input type="email" id="email" name="email" maxlength="100" required>
  • Password Input: Does not show the characters as they are typed.
<label for="password">Password</label>
<input type="password" id="password" name="password" maxlength="20" required>
  • Number Input: 
<label for="age">Age</label>
<input type="number" id="age" name="age" min="0" max="120">
  • Number Input (with decimals):
<label for="price">Price</label>
<input type="number" id="price" name="price" min="0" step="0.01">
  • Tel Input: Displays a telephone keypad in some devices with dynamic keypads.
<label for="phone">Phone Number</label>
<input type="tel" id="phone" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}">
  • Search Input: Removes line breaks from submission. Displays a search icon on some devices.
<input type="search" placeholder="Enter Search Term">
  • Hidden Input: Not displayed to user. The value attribute gets submitted with the form.
<input type="hidden" name="user_id" value="10235">
  • URL Input: Validates URL format. You can add a pattern attribute to be more narrow.
<label for="website">Website</label>
<input type="url" name="website" id="website" placeholder="https://www.example.com" size="50">
  • Date Input: Displays a date picker. 
<label for="birthdate">Birthdate:</label>
<input type="date" name="birthdate" id="birthdate" min='1900-01-01'>
  • Datetime-local Input: Displays a date-time picker without timezone. 
<label for="starts">Starts:</label>
<input type="datetime-local" name="starts" id="starts" min="2010-01-01" max="2025-12-31">
  • Time Input: Displays time picker or wheel. Step sets the increments in seconds (600 is 10 minutes).
<label for="starts">Starts:</label>
<input type="time" name="starts" id="starts" step="600>
  • File Input: Upload a file from the user's computer. You must add enctype attribute to the form element. The accept property limits the accepted file types.
<form enctype="multipart/form-data" ...>
  <label for="pic">Select from files</label>
  <input type="file" name="pic" id="pic" accept="image/*,.pdf">
Default CSS
label { 
  display: inline-block;
  cursor: default
}
input { 
  display: inline-block;  
  margin: 0em;
  padding: 1px 2px;
  border-width: 2px;
  border-style: inset;
  border-color: -internal-light-dark(rgb(118, 118, 118), rgb(133, 133, 133)); cursor: text;
}
input[type="text" i] {
  padding: 1px 2px;
}
Input Element Attributes:
id="title" use id attribute to connect it to the label element.
name="title" the field name submitted with the form data.
size="100" the width of the field in number of characters. Default is 20.
autofocus automatically places the user's cursor in the form field.
placeholder="Some text" displays text in the field without setting the value.
value="Initial Value" sets the initial value of the field.
readonly user can read the value but not change it.
disabled disables the form field.
Validation Attributes:
required makes the field required
minlength="2" maxlength="255" Sets the min/max length of characters.
min="1" max="100" step="10" Sets the min/max/step increment number values.
min="2020-01-01" max="2050-12-31" step="600" Sets the min/max date and step increments in seconds.
pattern="[A-Za-z]{10}" Input must match the regexp pattern.
Textarea Element
  • For multiple lines of text.
  • Can use the same attributes as the input element except size (use cols) and value, which is just placed between the opening and closing textarea tags.
  • Additionally, has rows and cols attributes. Default is 2 rows.
<label for='content'>Content</label>
<textarea id='content' name='content' rows='10' required></textarea>
Select Box - select one
<label for='category'>Category</label>
<select type='select' id='category' name='category' required>
  <option value=''>-- Select an Option --</option>
  <option value='Technology'>Technology</option>
  <option value='Economy'>Economy</option>
  <option value='Politics'>Politics</option>
</select>
  • The first option is the default value.
  • You can set the first value to an empty string with no text or "Select an Option".
  • To preselect a different option than the first, add the select attribute.
Radio Buttons - select one
<label>Category</label><br>
  <input type='radio' id='technology' name='category' value='Technology' checked>
  <label for='technology'>Technology</label>
  <input type='radio' id='economy' name='category' value='Economy'>
  <label for='economy'>Economy</label>
  <input type='radio' id='politics' name='category' value='Politics'>
  <label for='politics'>Politics</label>
  • Each input must have a value and a label. Same name value for all inputs.
  • Checked attribute selects the input as default.
Check Boxes - select multiple
<label>Tags</label><br>
  <input type="checkbox" id="tags-js" name="tags" value="javascript">
  <label for="tags-js">JavaScript</label>
  <input type="checkbox" id="tags-html" name="tags" value="html">
  <label for="tags-html">HTML</label>
  <input type="checkbox" id="tags-css" name="tags" value="css">
  <label for="tags-css">CSS</label>
  • Each input must have a value and a label. Same name value for all inputs.
  • Checked attribute selects an input as default (can be multiple).

CSS

Ref: MDN_Guides:Images&forms

Article form example

  • Bootstrap classes. 
  • Fieldset with legend elements. 
  • Fields: text, textarea, single checkbox, select box, radio buttons, check boxes.
  • Submit and cancel buttons.
Article form example.
<h1 class='mt-4'>Create Article</h1>
<hr>
<form method='POST' action="">
  <div class='form-group'>
    <label for='title'>Title</label>
    <input type='text' id='title' name='title' 
        class='form-control' maxlength='200' required>
  </div>
  <div class='form-group'>
    <label for='content'>Content</label>
    <textarea id='content' name='content' rows='10' class='form-control' required></textarea>
  </div>
  <div class='form-check'>
    <input type='checkbox' id='published' name='published' class='form-check-input' value=true checked>
    <label for='published' class='form-check-label'>Publish</label>
  </div>

  <div class='form-group mt-3'>
    <label for='category'>Category</label>
    <select type='select' id='category' name='category' class='form-control' required>
      <option value=''>-- Select an Option --</option>
      <option value='Technology'>Technology</option>
      <option value='Economy' selected>Economy</option>
      <option value='Politics'>Politics</option>
    </select>
  </div>

  <fieldset>
    <legend>Category</legend>
    <div class='form-check-inline'>
      <input type='radio' id='technology' name='category' class='form-check-input' value='Technology' checked>
      <label for='technology' class='form-check-label'>Technology</label>
    </div>
      <div class='form-check-inline'>
      <input type='radio' id='economy' name='category' class='form-check-input' value='Economy'>
      <label for='economy' class='form-check-label'>Economy</label>
    </div>
    <div class='form-check-inline'>
      <input type='radio' id='politics' name='category' class='form-check-input' value='Politics'>
      <label for='politics' class='form-check-label'>Politics</label>
    </div>
  </fieldset>

  <fieldset class="mt-3">
    <legend>Tags</legend>
    <div class='form-check-inline'>
      <input type='checkbox' id='tags-javascript' name='tags' class='form-check-input' value='javascript'>
      <label for='tags-javascript' class='form-check-label'>JavaScript</label>
    </div>
    <div class='form-check-inline'>
      <input type='checkbox' id='tags-html' name='tags' class='form-check-input' value='html'>
      <label for='tags-html' class='form-check-label'>HTML</label>
    </div>
    <div class='form-check-inline'>
      <input type='checkbox' id='tags-css' name='tags' class='form-check-input' value='html'>
      <label for='tags-css' class='form-check-label'>CSS</label>
    </div>
  </fieldset>

  <div class='form-group mt-3'>
    <input type="submit" value="Save" class='btn btn-primary'>
    <a href='/articles' class='btn btn-outline-secondary float-right'>Cancel</a>
  </div>
</form>

User form example: 

  • Bootstrap classes with cards. 
  • Fieldset element. 
  • Fields: text, email, password, number, date, tel, file (image).
  • Submit button and link to login page.
User form example.
<div class="card">
  <div class="card-header bg-dark text-white text-center">
    <h2>Sign Up</h2>
  </div>
  <form method="POST" action="" enctype="multipart/form-data">
  <div class="card-body">
    <div class='form-group'>
      <label for="name">Name</label>
      <input type="text" name="name" class="form-control" required>
    </div>
    <div class="form-group">
      <label for="email">Email</label>
      <input type="email" name="email" class="form-control">
    </div>
    <fieldset class='card bg-light p-3'>
      <div class="form-group">
        <label for="password">Password <i>(6 characters minimum)</i></label>
        <input type="password" name="password" class="form-control">
      </div>
      <div class="form-group">
        <label for="password_confirmation">Password Confirmation</label>
        <input type="password" name="password_confirmation" class="form-control">
      </div>
    </fieldset>
    <div class='row mt-3'>
      <div class='col-md-4'>
        <label for="age">Age</label>
        <input type="number" id="age" name="age" min="0" max="120" class="form-control">
      </div>
      <div class='col-md-4'>
        <label for="birthdate">Birthdate:</label>
        <input type="date" name="birthdate" id="birthdate" min='1900-01-01' class="form-control input">
      </div>
      <div class='col-md-4'>
        <label for="phone">Phone Number</label>
        <input type="tel" id="phone" name="phone" placeholder="415-555-5555" class="form-control">    
      </div>
    </div>
    <div class="mt-3 mb-1">Profile Picture</div>
    <div class='custom-file'>
      <label for="pic" class="custom-file-label">Select from files</label>
      <input type="file" name="pic" id="pic" accept="image/*,.pdf" class="custom-file-input">
    </div>
  </div>
  <div class="card-footer">
    <div class="form-group">
      <input type="submit" value="Sign Up" class="btn btn-primary">
      <span class="float-right">Already a member? <a href="/login">Log in</a></span>
    </div>
  </div>
  </form>
</div>

Bootstrap Forms

Ref: getbootstrap.com/docs/5.2/forms/overview
<div class="mb-3">
  <label for="id" class="form-label">Label Here</label>
  <input type="text" class="form-control" id="__">
</div>
Text area: <textarea class="form-control" id="__" rows="_"></textarea>
Checkbox and Radio Buttons: Set type to checkbox or radio. "Value" gets submitted with the form.
<input class="form-check-input" type="__" value="__" id="__">
<label class="form-check-label" for="id">Label Here</label>
Select box: Id is the form field name. The selected "value" gets submitted with the form.
<select id="__" class="form-select">
  <option selected>Select item</option>
  <option value="__">Value 1</option> <!-- list other options below -->
</select>
Form example
<form>
  <div class="mb-3">
    <label for="title" class="form-label">Title</label>
    <input type="text" class="form-control" id="title">
    <div class="form-text">Optional explanation text here.</div>
  </div>
  <div class="mb-3">
    <label for="content" class="form-label">Content</label>
    <textarea class="form-control" id="content" rows="5"></textarea>
  </div>
  <div class="form-check mb-3">
    <input class="form-check-input" type="checkbox" value="true" id="publish">
    <label class="form-check-label" for="publish">Publish</label>
  </div>
  <div class="form-check">
    <input class="form-check-input" type="radio" name="status" value="draft" id="draft">
    <label class="form-check-label" for="draft">Draft</label>
  </div>
  <div class="form-check mb-3">
    <input class="form-check-input" type="radio" name="status" value="published" id="published" checked>
    <label class="form-check-label" for="published">Published</label>
  </div>
  <div class="mb-3">
    <label for="category" class="form-label">Category</label>
    <select id="category" class="form-select">
      <option selected>Select category</option>
      <option value="html">HTML and CSS</option>
      <option value="database">Database</option>
      <option value="javascript">JavaScript</option>
    </select>
  </div>
  <button type="submit" class="btn btn-primary mt-4">Submit</button>
</form>

Links | ButtonsGo to video for this category

Links

Ref: MDN:a
URL format: scheme://host[:port][/]path[?query][#fragment]
Example: https://www.example.com/articles/learn-html#tables
URL breakdown
URL (Uniform Resource Locator): a reference to a web resource that specifies its location on a computer network and a mechanism for retrieving it. URLs are most often associated with web addresses (http/https), but are also used for file transfer (ftp), email (mailto) and many other applications.
  • Scheme (aka protocol): http, https, ftp, mailto, file, and data. Scheme is followed by ://
    • HTTP vs HTTPS: HTTP stands for hypertext transfer protocol. The "S" in HTTPS stands for secure. HTTPS uses TLS (SSL) to encrypt normal HTTP requests and responses. This protects against data being intercepted by third parties.
  • Host: an ip address or a registered name (e.g., www.example.com) that has an assigned ip address. It consists of a subdomain and a domain name, ending with the top level domain:
    • Subdomain: most often is www (indicating the domain is part of the worldwide web) but the site can create their own subdomains such as articles.example.com instead of www.example.com/articles. 
      • Web addresses without a subdomain are called naked domains: https://example.com
    • Domain Name: example.com. 
      • Top Level Domain: is the last part of the domain name after the . delimiter. Common examples: com, org, gov, net, info, co. 
  • Path: /articles/learn-html
  • Query string: begin with ? and generally containing a sequence of attribute-value pairs separated by a delimiter.
    • /articles?title=HTML Query string with title value.
    • /articles?title=Learn%20HTML Replace spaces with %20.
    • /articles?title=HTML&Author=Carey Query string with title and author values.
  • Fragment: begin with #. Takes the user to the page and scrolls to the element id on that page.
    • /articles/learn-html#tables
Hyperlinks use the anchor tag with the hyperlink reference attribute:
<a href="https://www.example.com">Example</a>
Target Attribute: Open the link in another browser window:
<a href="https://www.example.com" target="_blank">Example</a>
Generally don't include target.
  • As a general rule, don't include the target. The user can open the link in another window by pressing the command key when they click on the link. If the intention is to open the link in a different window then include it.
Absolute Links: Include the full URL.
Relative Links: For links within the same website, the domain name is excluded.
  • Link to another page relative to your site's root route.
<a href="/articles/learn-css">Learn CSS</a> Begins with a forward slash.
  • Link to another page relative to the current directory.
<a href="learn-css">Learn CSS</a> Excludes the preceeding slash.
Link to a specific location on a page:
On the page you are linking to, add an id to the element you want the link to go to:
<div id="tables>...</div>
At the end of the hyperlink, add a fragement with that id: 
<a href="/articles/learn-html#tables">Learn HTML Tables</a>
If the id is on the same page as the link then just include the fragment:
<a href="#tables">Tables</a>
Button as link:
<a href="http://www.example.com"><button>Go to example.com</button></a>
Image as link:
<a href="http://www.example.com"><img src="/pic.png" alt="text"></a>
Email link: (opens their default email when clicked)
<a href="mailto:support@example.com">Contact Us</a>
Add a subject: 
<a href="mailto:support@example.com?Subject=Some Subject">Contact Us</a>

CSS

Ref: MDN_Guides:Styling_links 
Four states of a link by pseudo-class and their default CSS:
  • a:link Unvisited link. Underlined with blue text
  • a:visited Visited link. Underlined with purple text.
  • a:hover While user's cursor is hovering over link. Cursor changes to pointer.
  • a:active While user is clicking on link. Underlined with red text
Default CSS
Use the below order:
a:link {
  color: blue; /* remove with: inherit or unset */
  text-decoration: underline; /* remove with: none */
}
a:visited {
  color: purple;
}
a:hover {
  cursor: pointer; /* remove with: default */
}
a:active {
  color: red;
}

Bootstrap - stretched links

Ref: getbootstrap.com/docs > click Helpers: stretched link
<a href="#" class="stretched-link">Go somewhere</a>
Stretched links expand the clickable location from just the anchor element, to include its parent element. Parent must have class "position: relative" or "card".
Example
<div class="position-relative">
  <h5>Clicking here also activates the below link</h5>
  <a href="https://www.example.com" class="stretched-link">Go to site</a>
</div>

Buttons

Ref: MDN:button
<button type="button">Click Me</button>
Button with type="button" does not do anything without attaching JavaScript or making it a link.
<button type="button" onclick="console.log('clicked button')">Log click</button>
<a href="https://google.com"><button type="button">Go to Google</button></a>
Default CSS
Chrome default CSS:
button {
    display: inline-block;
    cursor: default;
    font: 400 11px system-ui;
    color: black;
    text-shadow: none;
    text-align: center;
    background-color: white;
    box-sizing: border-box;
    margin: 0em;
    padding: 1px 7px 2px;
    border-width: 1px;
    border-style: solid;
    border-color: #d8d8d8 #d1d1d1 #bababa; /* progressively darker greys */
}

Form submit buttons

  • Button default type is "submit". If the button is not in a form element it will behave as if the type was "button".
  • Form submit buttons can be input or button elements with type submit. The appearance and functionality are identical. Difference: You can style button text but not input text.
<button type="submit">Save</button> 
<input type="submit" value="Save">

Form Reset: Form elements can also have a reset button which will clear all form fields (not commonly used):
<button type="reset">Reset Form</button>

Bootstrap - buttons

Ref: getbootstrap.com/docs/5.2/components/buttons | badge
.btn
.btn-size - sm small, lg large
.btn-color - primary blue, secondary gray, dark blackish
.btn-outline-color - Color is for text and border. Background is clear
Examples
Blue button: <button class="btn btn-primary">Click me</button>
Grey button: <button class="btn btn-secondary">Click me</button>
Blackish button: <button class="btn btn-dark">Click me</button> 
Blue outline button: <button class="btn btn-outline-primary">Click me</button>
Small blue button: <button class="btn btn-primary btn-sm">Click me</button>
Large blue button: <button class="btn btn-primary btn-lg">Click me</button>
Link as a button: <a href="___" class="btn btn-primary">Button link</a> 

ImagesGo to video for this category

Ref: MDN:img

Image formats

  • Png preferred when: Image has a transparent background. Image quality is important (e.g., logos). Your site only has a few images.
  • Jpg preferred when: Your site has many images with large png file sizes.
Most common web image formats.
Bitmap Images:
  • png: Allows transparent backgrounds. Uses lossless file compression resulting in better quality than jpg.
  • jpg/jpeg: Does not allow transparent backgrounds. Uses lossy file compression resulting in a smaller file size than png but lower image quality.
    • The jpg extension is more commonly used than jpeg but either can be used.
  • gif: For short animations. Can also be plain images.
Vector Images:
  • svg: Uses vector graphics instead of a pixel grid. Can scale without losing image quality. 

Lossless vs Lossy image file compression:
  • Lossy data compression eliminates data from the file. The compression algorithm analyzes the file data and removes data deemed expendable from the image. It approximates the original data as opposed to exactly duplicating it. This decreases file size but also image quality. Lossy images cannot be restored to their original version once compressed.
  • Lossless data compression allows the original data to be reconstructed from the compressed data. The algorithm reduces the file size by eliminating redundant data. File size is larger than with lossy compression.

Bitmap vs Vector:
  • Bitmap (aka raster) images are made up of pixels in a grid. Pixels are tiny squares each with a specific color. Put together they form an image. They lose quality when resized larger. Photographs are bitmap images.
  • Vector image files contain mathematical formulas setting shapes, colors and placement that form the image. Vector files can be resized without quality loss. For the web, vector images can either be converted to png or gif images, or viewed as svg elements.

Svg images

Svg images can either be placed directly in the HTML document. <svg ...>
Or the svg file can be the src value in an img element <img src="path/img.svg">

Img Element

<img src="/path/pic.png" alt="Image description">
  • If the image is strictly for decorative purposes, set alt to empty text: <img alt=""> 
Attribute details
  • src: Source attribute is the path to the image file. It is required.
  • alt: Provide a text description of the image. It is not required but very useful for two things: 
    1. If the image fails to load for some reason, the alt text is displayed in its place.
    2. For accessibility. It is read when the screen reader is turned on. Screen readers announce "image" when reading alt text, so don't include "image" in the description.
For more info on alt: developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/alt

Src: Absolute and Relative Paths

Absolute Path: URL to the image in another website: 
<img src="https://example.com/path/to/some-pic.png">
Relative Path: path to the image file in your project.
<img src="/assets/images/some-pic.png"> 
Examples
Absolute Path:
  • < img src="https://picsum.photos/300/200">
  • If the src value does not include a protocol (e.g., https://), the browser assumes it is a relative path.
Relative Paths:
  • Generally, your site should have a folder for images.
  • <img src="/public/images/filename.png"> Paths beginning with a / start at the site's root directory. 
  • <img src="filename.png"> Paths without a preceeding / start from the current page's directory. This file is in the same directory as the current page.
  • <img src="images/filename.png"> Image file is down one directory in images.
  • <img src="../filename.png">  To go up one level to the parent directory use two dots
  • <img src="../../filename.png"> Going up two directories
  • <img src="../images/filename.png">  Going up to the parent directory then down to a different child directory (images in this case)


Dimensions - Width and Height

You can set the image width and height using HTML attributes or CSS properties.
  • Img element attributes:
<img id="pic" src="pic.png" alt="description" width="400" height="300">
  • CSS style rule properties:
#pic { width: 400px; height: 300px; }
Attributes vs CSS properties.
  • If you don't specify the image dimensions it will default to auto and use the intrinsic dimensions of the image file.
  • By adding dimensions, if there is a delay loading the image the browser will set aside space for the image based on the dimensions. This will prevent the browser having to readjust the content when the image loads.
  • Whether you use size attributes or CSS properties is a matter of preference.
  • Width and height attribute values are the number of pixels. Do not add px.
  • CSS width and height properties override width and height img attributes.
  • If you set width but not height (or vice versa) the browser will calculate and use the image's aspect ratio to set the missing dimension.

Intrinsic Size, Aspect Ratio, Resolution

  • Intrinsic size: The width and height defined in the image file itself.
  • Images render at their intrinsic size if no dimensions are set.
  • Aspect ratio: ratio of width to height. Most common photo ratios are 4:3, 3:2, 16:9.
  • Resolution: Number of pixels displayed per inch (PPI). For photos 72 is common.
Change image's intrinsic dimensions (and resolution)
  • If you set dimensions in the attributes or CSS that don't match the image's actual size, the browser will have to adjust the image size when rendering the page.
  • To avoid that, you can change an image's dimensions.
  • On a Mac: Locate the image in Finder > double click the image file to open it in Preview > Tools menu > Check Scale Proportionally > Change width or height. 
    • You can also reduce the file size by setting the resolution to 72 pixels/inch which is usually fine for the web (but test it to make sure).

Image as link

  • To make an image a hyperlink, place the img element inside an anchor tag.
Example
<a href="http://www.learn-about-dolphins.com">
  <img src="images/dolphin.jpg" alt="Jumping dolphin">
</a>

CSS

Ref: MDN_Guides:Images&forms
Img Browser Default CSS
img { 
  display: inline; /* inline, block, inline-block, none */
  vertical-align: bottom; /* bottom, middle, top */
}
  • The image is inline with other text or elements, but the line height is set to the image's height.
  • The image aligns with the bottom of the line.

Alignment:

Center image: Two options.
  • Apply to parent element: .pic-parent { text-align: center; } 
  • Apply to img element: .pic { display: block; margin-left: auto; margin-right: auto; }
Align image right: Two options.
  • Apply to parent element: .pic-parent { text-align: right; } 
  • Apply to img element: .pic { display: block; margin-left: auto; }
Float image: have the rest of the page flow around the image.
  • Float image to the left: .pic { float: left; margin-right: 1rem; } 
  • Float image to the right: .pic { float: right; margin-left: 1rem; }
Vertical alignment: By default, everything on the image row aligns to the bottom.
  • Align row to top: .pic { vertical-align: top; } 
  • Align row to middle: .pic { vertical-align: middle; }
Examples
Align the below image:
<div class="parent-of-pic">
  <img class="pic" src="/images/my-pic.png" alt="">
</div>

Align image to center of row:

Apply this class to the image's parent element: 
.parent-of-pic { text-align: center; } 
Or, apply this class directly to the img element: 
.pic { display: block; margin-left: auto; margin-right: auto; }

Align image to right of row:
Apply this class to the image's parent element: 
.parent-of-img { text-align: right; } 
Or, apply this class directly to the img element: 
.img { display: block; margin-left: auto; }

Align the below image with text:
<div class="parent-of-pic">
  Some text.
  <img class="pic" src="/images/my-pic.png" alt="">
</div>

Float image: have the rest of the page flow around the image.
Float image to the left. The text will flow to the right of it: 
.pic { float: left; margin-right: 1rem; } 
Float image to the right. The text will flow to the left of it: 
.pic { float: right; margin-left: 1rem; }

Vertical alignment: The text that is on the same row as the image will align to the bottom by default.
Align everything in the row to the top:
.pic { vertical-align: top; } 
Align everything in the row to the middle: 
.pic { vertical-align: middle; }

Make image responsive

  • Set the width on the image or in the CSS style rule. Display image at its set width (or intrinsic width if not set).
  • max-width: 100%; height: auto; Image will never be larger than the available width.
Example
Set the width and height in the img element. Width could alternatively be set in the CSS.
<img src="pic.jpg" alt="" width="800" height="450" class="img-responsive">

In the stylesheet, set max-width to 100%. If the available width is less than the image width, the image will shrink to the available width.
Set height to "auto" so it will automatically resize itself when the width changes. It will use the image's intrinsic aspect ratio which is 16:9 in this case. 
.img-responsive {
  max-width: 100%;
  height: auto;
}

Opacity: Make an image partially transparent.

Opacity property value range: 0.0 to 1.0. Higher numbers are less transparent.
#pic { opacity: 0.5; } /* sets opacity to 50% */

Figure and figcaption elements:

For layout purposes you may place an image in a figure element:
<figure><img src="angry-cat.png" alt="Angry cat"></figure>
Default CSS, ex. with a caption
  • Default CSS:

figure { display: block; margin: 1em 40px; }
figcaption { display: block; }
  • Example:
    • Image element has max-width set to 100%, meaning it won't display wider than the image width (the width attribute/property if set or the intrinsic width if not) or with width of the screen.
    • The image is placed inside a figure element with a border. Figure is a block element.
    • The figure element has a style rule of float: left, so it will align left, and other elements will flow around it.
    • The fig-caption style rule centers the text, and gives it a black background.

CSS:
.pic { 
  width: 400px; /* same as the image's intrinsic width */
  height: 300px; /* same as the image's intrinsic height */
  max-width: 100%;
}
.figure {
  float:left;
  border: 1px solid black;
  border-radius: .25rem;
}
.figcaption { 
  text-align: center; 
  background-color: black; 
  color: white; 
  font-size: 1.5rem;
}
HTML:
<figure class="figure">
  <figcaption class="figcaption">Angry cat</figcaption>   
  <img src="angry-cat.png" alt="Angry cat" class="pic">
</figure>

Background image

Ref: MDN_Guides:Backgrounds_and_borders
Put background styling, including images, in the body selector:
body { background-image: url('wallpaper.png'); }
By default, the image is repeated so it covers the entire element.
Change the repeat, scroll/fixed, position, background color, image opacity.
Background-color: You can set a background color alone or in addition to an image.
body { background-color: #fbfbf8; } /* Off White */

Background-repeat property: default value is repeat.
body { background-image: url(wallpaper.png); background-repeat: repeat; }
Other values:
  • no-repeat To not repeat the image. 
  • repeat-x To repeat along the x axis (i.e., one horizontal row).
  • repeat-y To repeat along the y axis (i.e., one vertical column).
  • space Images repeat but instead of clipping images that don't completely fit, the non-fitting images on the right and bottom are left out and space is added between images to compensate.
  • round Similar to space except instead of using space between the images to make them fit, the images expand along the x axis. They are still clipped on the y axis.

Background-position property: Default position is left top. 
body { background-image: url(wallpaper.png); background-position: left top; }
  • To change it horizontally change left to center or right.
  • To change it vertically change top to center or bottom.
  • So to center it at the top:background-position: center top;
  • Or use x% and y% relative to the page: background-position: 50% 0%;
  • There are other ways as well. See MDN:background-position

background-attachment property: default is scroll.

body { background-image: url(wallpaper.png); background-attachment: scroll; }

  • background-attachment: fixed; Makes the background image fixed.
Change background-image image opacity: 
  • You can't set it directly. 
  • One workaround is to add a linear-gradient value set to equal rgba values.
  • Rgba uses the three-channel red-green-blue color model. The fourth channel is alpha which sets the opacity.
  • Opacity is expressed as a number between 0.0 and 1.0, with lower numbers being more transparent.

body { 
  background-image: linear-gradient(rgba(255, 255, 255, 0.5), 
      rgba(255, 255, 255, 0.5)),
      url('wallpaper.png');
}

Favicon

Use an ico or png formatted image. Link to it in the head element:
<link rel="icon" type="image/x-icon" href="/images/favicon.png">

Bootstrap Images

Ref: getbootstrap.com/docs > click Content: Images
  • img-fluid make image responsive.
  • rounded round the corners.
  • img-thumbnail add 1px border with rounded corners.
  • Images with captions:
<figure class="figure">
  <img src="" alt="Image text" width="150" height="150" class="figure-img">
  <figcaption class="figure-caption">Image caption here.</figcaption>
</figure>
Image Alignment: (Image takes up whole line).
  • mx-auto d-block center image. | ms-auto d-block align image to right.
  • Or wrap image in a div with class text-center to center or text-end to align right.
Image Float: (other elements will wrap around the image).
  • float-start Float image to the left. | float-end float to right. Add appropriate margins.
Examples
  • Responsive image with rounded corners:
<img src="path/pic.png" alt="Image Text" width="150" height="150" class="rounded img-fluid">


  • Image with Caption:
<figure class="figure">
  <img src="path/pic.png" alt="Image Text" width="150" height="150" class="rounded figure-img img-fluid">
  <figcaption class="figure-caption">Image caption here.</figcaption>
</figure>


Image Alignment: (Image takes up whole line)
  • Align image by converting display from inline to block and setting margin:
    • Align to center: Change img display from inline to block. Set left and right margins to auto.
<img src="path/pic.png" class="mx-auto d-block" alt="Image Title" width="150" height="150">
    • Align to right: Change img display from inline to block. Set left (aka start) margin to auto.
<img src="path/pic.png" class="ms-auto d-block" alt="Image Title" width="150" height="150">
  • Alternatively, align image by wrapping it with a div and using text align classes.
    • Align to center: 
  <div class="text-center">
    <img src="path/pic.png" class="rounded" alt="Image Text" width="75" height="75">
  </div>
    • Align to right: 
  <div class="text-end">
    <img src="path/pic.png" class="rounded" alt="Image Text" width="75" height="75">
  </div>


Image Float: (Other elements will wrap around it)
  • Align image to the left. Include margin to the side and bottom (and potentially top).
<img src="path/pic.png" alt="Image text" width="150" height="150" class="float-start me-3 mb-2">
  • Align image to the right. Include margin to the side and bottom.
<img src="path/pic.png" alt="Image text" width="150" height="150" class="float-end ms-3 mb-2">

Bootstrap Icons

Ref: icons.getbootstrap.com
To use the icons either:
  • Download SVG files. Place in project. Use in tag: <img src=ICON-FILE.svg>
  • Add CDN link to head element. Use web font class: <i class="bi bi-ICON-NAME">< /i>
Examples
Method 1: 
  • Download the specific SVG files you want to use. 
  • Place them in your images directory of your project.
  • Access them from the img tag in the src attribute.
<img src="images/hand-thumbs-up.svg" alt="Thumbs up icon">


Method 2:
  • In your head element, link to the Bootstrap icons css file on their CDN.
  • The icons are accessed as CSS classes. Place the class in the "i" element without content.
<head>
...
<link rel="stylesheet" href="CDN URL HERE /font/bootstrap-icons.css">
</head>
<body>
... <i class="bi bi-hand-thumbs-up"></i>
</body>

CSS Introduction including BootstrapGo to video for this category

Ref: MDN:CSS | MDN Guides:CSS | MDN:CSS properties index 
       W3schools:CSS

Default styles / user-agent-stylesheet.
  • Each browser uses a rendering engine to draw the HTML/CSS web page. Chrome, Edge, and Opera use a fork of Webkit called Blink. Safari uses Webkit. Firefox uses Gecko.
  • And they include a stylesheet called user-agent-stylesheet that provides default styles for each element.
  • These styles are overridden by your CSS.
  • You can't access the stylesheets directly. However, you can view the styles with these links:
  • Chrome: You can also create an HTML document with HTML but no CSS.
    • Open the HTML document in Chrome.
    • Assuming DevTools is installed, right click the page > Inspect (to open DevTools)
    • In the Elements tab click on an element. 
      • To view the default style rules directly impacting that element click the styles tab.
      • To view all styles impacting the element, direct and indirect, click the computed tab.
Definitions
  • CSS: Cascading Style Sheets
  • Style rule: sets the style for a specified HTML element. 
  • A style rule has two main parts: 
    • Selector: the HTML element(s), class(es), id(s), etc. you want to style.
    • Declaration: specifies how content described by the markup looks. 
  • A declaration consists of:
    • Property: the style attribute you want to change. Style attributes affect how the user's computer displays text and graphics. In the example, color and font-size are the properties.
    • Value: is what you want the style attribute to be. In the example blue and 14px are the values.

Syntax and style guidelines:

Ref: Google:HTML-CSS Style Guide
  • User lower case letters for tags, id names, class names, properties. 
  • Separate multiple words with hyphens.
  • Use semicolons after every declaration.
  • Use single quotes: font-family: 'Times New Roman';
  • For style rules use separate lines for each property:
body {
  font-size: 14px;
  background-color: #fbfbf8; 
}
  • Optionally, put short style rules on one line:
body { font-size: 14px; background-color: #fbfbf8; }
  • Comments: /* Comments here */

Selectors

ref: MDN Guides:Selectors | MDN:Selectors

Basic Selectors:
  • Tag: tag-name { declarations } ex: h1 { color: navy }
  • ID: #id-name { declarations } ex: #article-title { color: navy }
  • Class: .class-name { declarations } ex: .titles { color: navy }
  • Attribute: [attribute="value"] { declarations } ex: [type="submit"] { cursor: pointer; }
  • Universal: * { declarations } applies to all elements. ex: * { color: navy }
  • Not: sel1:not(sel2) { ... } ex all h1 except id='topic': h1:not(#topic) { color: navy }
Explanations and examples
Tag:
  • Use tags to set the general styles for your site rather than the browsers' default CSS. 
    Ex: body { font-size: 14px }
ID:
  • Use IDs when the style will be unique to one element in the HTML document.
  • Add the ID attribute to the opening HTML tag. 
    Ex: <h1 id="article-title">
  • In the CSS stylesheet, create the style rule with a hash sign # followed by the id name as the selector. 
    Ex: #article-title{ text-align: center; color: Navy; }
Class:
  • Use classes when the same style will be applied to multiple elements.
  • Add the class attribute to the opening HTML tag. 
    Ex: <form class="standard-form">
  • To assign more than one class to an opening tag, separate the classes with a space. 
  • Ex: <div class="standard-form bg-dark">
  • In the CSS stylesheet, create the style rule with a period . followed by the class name as the selector. 
    Ex: .standard-form { margin: 10px 20px; padding: 15px 20px; }
Attribute: 
  • Used to style HTML elements that have specific attributes, not just class and id. Often used with forms.
  • use square brackets [] around the attribute. 
    Ex: [type="submit"] { cursor: pointer; }
Universal:
  • Delimited with *. Applies style to all elements.
    Ex: * { color: navy }
Grouping Selectors:
  • Delimited by a comma. Used to apply the same style rules to multiple selectors: 
  • Syntax: selector1, selector2 { declarations }
  • ex: h1, h2, h3, h4, h5, h6 { color: MidnightBlue; }
Combine selectors - must satisfy both
  • tag-name.class-name { declarations } ex: h1.titles { color: navy }
  • tag-name#id { declarations } ex: h1#some-id { color: navy }
  • tag-name[attribute="value"] { declarations } ex: input[type="submit"] { cursor: pointer; } 
Combinators:
Descendant combinator (space delimiter): 
  • Selects all nodes that are descendants of the first element.
    Syntax: selector1 selector2 { declarations }
    Ex: .articles p { color: navy; }
Child combinator (> delimiter):
  • Selects only nodes that are direct children of the first element.
    Syntax: selector1 > selector2 { declarations }
    Ex: .articles > h1 { color: navy; }
General sibling combinator (~ delimiter):
  • Selects siblings where one follows the other and they both share the same parent. There can be other elements between them.
    Syntax: selector1 ~ selector2 { declarations }
    Ex: .title ~ .content { color: navy; }
Adjacent sibling combinator (+ delimiter):
  • Selects the second element if it is both a sibling of and directly follows the first element.
    Syntax: selector1 + selector2 { declarations }
    Ex: .title + .author { color: navy; }
Examples
HTML:
<div class="articles">
  <h1 class="title">Learn CSS</h1>
  <p class="author">Joey R.</p>
  <div class="content">
    <p>Content goes here.</p>
    <p>More content here.</p>
  </div>
</div>

CSS:
Descendant combinator: .articles p { color: navy; } 
  • Applies to all p tags that descend from <div class="articles"> 

Child combinator: .articles > p { color: navy }
  • Applies to only the p tags that are direct children of <div class="articles>
General Sibling combinator: .title ~ .content { declarations }
  • Applies to any tags with class="content" that follow and are siblings of <h1 class="title">
Adjacent sibling combinator: .title + .author { color: navy; }

  • Applies to element with class="author" if it follows a sibling element with class="title".
Pseudo classes (: delimiter):
  • Selects elements based on state information. 
  • Syntax: selector:pseudo-class { property: value; }
  • Ex: input:focus { background-color: aquamarine } 
Full list: MDN:Pseudo-classes
Examples
button element: :hover, :active, :focus
  • button:hover { prop: val; } While cursor is over the element.
  • button:active { prop: val; } While button is being clicked.
  • button:focus { prop: val; } From clicked til user clicks elsewhere.
a element: :link, :hover, :active, :visited. See Links section.
:first-child, :last-child, :nth-child(x), nth-last-child(x)
  • p:first-child { prop: val; }  Applies style to the first p element only.
  • section > div:nth-child(3) { prop: val; } Applies to 3rd div under section element.
:root accesses the root element (generally the html element)
  • :root { prop: val; } equivalent to html { prop: val; }
input element :focus, :checked
  • input:focus { prop: val; } From clicked til user clicks elsewhere.
  • input[type="radio"]:checked { prop: val; } Once it's checked.
  • input[type="checkbox"]:checked { prop: val; } Once it's checked.
:required
  • input:required { prop: val; } Applies to input elements with the required attribute.
:invalid, :valid
  • Border color is red while input is not valid email syntax, blue when valid:
  • HTML: <input type="email" name="email" placeholder="Email" required>
  • CSS: input:invalid { border-color: red; }
  • CSS: input:valid { border-color: blue; }
:out-of-range
  • input:out-of-range { border-color: red; } Use when min/max attributes are applied.
 
Pseudo elements (:: delimiter):
  • Selects part of an element.
  • Syntax: selector::pseudo-element { property: value; }
  • Ex: p::first-letter { font-size: 2em; } Change font-size of first letter in all p elements.
Full list: MDN:Pseudo-elements
Examples
::first-letter
  • Apply to the first letter of every p element:
  • p::first-letter { font-size: 2em; } 
::first-line
  • Apply to the first line of every p element:
  • p::first-line { color: navy; } 
::selection
  • Make selection white letters, navy background:
  • ::selection { color: white; background-color: navy; } 
  • Make selection in a p element have white letters, navy background:
  • p::selection { color: white; background-color: navy; } 
::before, ::after
  • Insert a green X in front of elements with class="approved":
  • .approved::before { content: "X ", color: green; } 

CSS Placement / Cascade Order

External file
  • This is generally the preferred placement.
  • Create a separate css file. Best practice is to put it in a stylesheets directory:
// public/stylesheets/styles.css
h1 { color: darkBlue; }

  • Link to the file in the HTML page head element:
<link rel="stylesheet" href="/public/stylesheets/styles.css">

Internal Style Sheet
  • Not recommended in the final product, but can be useful when developing.
  • Place in the HTML page's head element:
<style type="text/css"> /* Add your CSS below */
h1 { color: darkGreen; }
</style>


Inline Style:
  • Add a style attribute directly to an HTML element:
<h1 style="color: darkRed">Some text</h1>
  • Use semicolons to separate multiple properties.
<h1 style="text-align: center; color: darkRed">Some text</h1>

Override precedence with !important:
h1 { color: darkBlue !important; }
Order of precedence
If there are multiple styles specified, the order of priority is:
  1. Style rule with !important appended.
  2. Inline style - inside an HTML element (highest priority).
  3. Stylesheet (internal or external).
    • If there are multiple stylesheets, the last has higher priority.
  4. Browser default (lowest priority).
Multiple Stylesheets
  • Put links to the stylesheets in the head element in order of priority (lower priority first).
  • Alternatively link to one main stylesheet. Then at the top, import the other stylesheets:
// public/stylesheets/styles.css
@import url('https://fonts.googleapis.com/css?family=Lato');
body { font-family: Lato; }

Bootstrap

Ref: getbootstrap.com Docs tab has full documentation on Bootstrap classes.
Installation options (see website home page):
  • Copy CSS CDN link in the head. JavaScript CDN link just before the closing body tag.
  • Download and place bootstrap.min.css and bootstrap.bundle.min.js in your project.
  • In a Node.js project, install the NPM package.
Example
  • Linking to the Content Delivery Network then your own CSS file:
<head>
  ...
  /* Paste the CSS CDN link then the link(s) to your own CSS file(s) */
  <link rel="stylesheet" href="CDN URL HERE" integrity="STRING" crossorigin="anonymous">
  <link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
  ...
  <script src="CDN URL HERE" integrity="STRING" crossorigin="anonymous"></script>
</body>

  • Linking to Bootstrap placed in your project then your own CSS file. Change paths if yours differ:
<head>
  ...
  /* Paste the path to the minimized Bootstrap css and js files, then the link(s) to your own CSS file(s) */
  <link rel="stylesheet" href="/stylesheets/bootstrap.min.css">
  <link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
  ...
  <script src="/javascripts/bootstrap.min.js"></script>
</body>

  • In a Node.js project you can install the NPM package: npm install bootstrap

Color | LengthGo to video for this category

Color

Ref MDN: Applying_color | Color property
Ref W3Schools: Color_picker | Color_names
.box { 
  color: white; /* sets text color. Named color value */
  background-color: #000000; /* hex value */
  border-color: rgb(0,0,102); /* RGB value */
}
  • Color value notation options: named color, hex string, rgb(), rgba(), hsl(), hsla().
  • Hexadecimal string notation: syntax: #rrggbb ex: #000000 (black)
    • Optional: Three character shortcuts work in some cases (#000 for #000000).
    • Opacity: Append alpha value #rrggbbaa ex: #00000080 (50% opacity).
  • RGB functional notation: syntax: rgb(r,g,b) ex: rgb(0,0,102) (purple)
    • Opacity: Alpha value (0 to 1). rgb(r,g,b, a) ex: rgb(0,0,102,0.6) (60% opacity)
Explanations for hex values, RGB, and Alpha.
Hexadecimal numbers:
  • Decimal numbers have a base of 10. Two digit decimals have (10x10) 100 possibilities ranging from 00 to 99.
  • Hexadecimal numbers have a base of 16 and include characters 0-9 and a-f. Two digit hexadecimal numbers have (16x16) 256 possibilities ranging from 00 to ff.
  • Hex string #rrggbb contains three hexadecimal two digit numbers representing red, green and blue.
  • The value of each pair is a byte that represents the color's intensity ranging from low (00) to high (ff). 
rgb() notation: rgb(r,g,b)
  • The value for each color (red, green, blue) represents the least (0) to the most (255) intensity.
Alpha channel: 
  • Represents opacity. The higher the value the more opaque, the lower the value the more transparent.
  • Hex notation: You can add an alpha value at the end of a hex string:  #rrggbbaa (e.g., #00000080). The value is expressed as a two digit percent but in hexadecimal form. so 0% is 00, 50% is 80, 100% is ff. Setting 100% opacity is the same as not including an alpha.
  • rgba() notation: adds alpha as the fourth value expressed as a number from 0.0 to 1.0. The higher the number the more opaque, the lower the number the more transparent. Ex: rgba(0,0,102,0.5) purple 50% opaque.
Common colors: black #000000; white #ffffff; gray #808080; red #ff0000; blue #0000ff; green #008000; yellow #ffff00; purple #800080; brown #a52a2a; maroon #800000; olive #808000; navy #000080; teal #008080; silver #c0c0c0; fuchsia #ff00ff; lime #00ff00; Aqua #00ffff

Text Color and Background Color

color: #212529; Sets text color (grey-black)
background-color: #f5f5f5; White smoke color
CSS class: black box with white text
CSS
.black-box {
  color: white;  
  background-color: black;
  padding: .2rem 1rem;
  border-radius: .25rem;
}
HTML:
<h1 class="black-box">Heading Text Here</h1>

Bootstrap Colors

Ref: getbootstrap.com/docs > click Utilities: colors
Set color property with text-*, Set background-color with bg-*
  • primary blue #0d6efd;
  • secondary grey #6c757d;
  • success green #198754;
  • danger red #dc3545;
  • warning yellow #ffc107;
  • info light blue #0dcaf0;
  • light light grey #f8f9fa;
  • dark blackish #212529;
  • text-white white #ffffff; 
  • text-muted grey #6c757d; 
Examples
<h1 class="text-white bg-dark">Heading with a dark background</h1>
<p class="text-danger>Error message text in red</p>

Length and Percentages

Ref: MDN_Guides:Values_and_units

Length properties

Ref: MDN:length
  • Length is a CSS data type that represents a distance value. 
  • Common CSS properties that use length: width, height, margin, padding, border-width, font-size, text-shadow.

Length Units

Absolute Length Units
  • px: One pixel. Ex: body { font-size: 14px; } 
More info on px. Other absolute units
px: (1px = 1/96th of 1in). Pixels are relative to the viewing device. For low-dpi devices, 1px is one device pixel (dot) of the display. For printers and high resolution screens 1px implies multiple device pixels.

Other Absolute units (not commonly used):
  • cm: centimeters
  • mm: millimeters
  • in: inches (1in = 96px = 2.54cm)
  • pt: points (1pt = 1/72 of 1in)
  • pc: picas (1pc = 12 pt)
Relative Length Units
  • em: Sets the length relative to the font size of the element.
    Potential unexpected results if there are cascading font size changes.
    ex: .grow-font { font-size: 1.2em; }
  • rem: Sets the size relative to the root element <html> font size. Default: 16px.
    ex: .shrink-font { font-size: .8rem; }
Example
  • Web browsers have a base font-size of 16px as default. 
  • REM: This is what rem units are based on. To change that you must change the html element's font-size property (not the body element).
  • EM: em units are initially based on the browser default font-size. If font-size is changed in any ancestor elements then em is based on that changed font size.
  • Example:
<!DOCTYPE html>
<html>
<head>
  <style type="text/css">
    html { font-size: 10px; }
    .grow-font-em { font-size: 2em; }
    .grow-font-rem { font-size: 1.5rem; }
  </style>
</head>
<body>
<div>
  <h1>Relative CSS Length</h1>
  <p>Font size: 10px, inherited from the base font-size.</p>
  <div class="grow-font-em">
    <p>Font size: 20px, inherited from parent element.</p>
    <p class="grow-font-rem">Font size: 15px, based on 1.5rem.</p>
    <p class="grow-font-em">Font size: 40px, based on 2em x 2em.</p>
  </div>
</div>
</body>
</html>
  • Font-size is set to 10px on the html element, so used as the base for rem.
  • The first p element font-size is 10px.
  • There are a series of three p elements inside a div with class grow-font-em. This and its child elements now have a base font size of 2em which is 10px.
    • The first p element inherits the new base size of 20px.
    • The second p element font size is 1.5rem, calculated of the root font-size of 10, resulting in 15px.
    • The third p element font size is 2em on top of the new base of 20px, resulting in 40px.
Percentages
Ref: MDN:percentage
  • Percentage CSS data type: Defines a size relative to the element's parent element. 
  • Common CSS properties that can use percentages: width, height, margin, padding, font-size.
  • ex: .box { width: 50%; margin-left: 15%; padding: 10%; }
  • Margin and padding percentages, horizontal and vertical, are based on the inline (i.e., horizontal) width.
Example
CSS:
.box { width: 20%; margin-left: 30%; padding: 10%; background-color: blue; }
.content { background-color: grey; }
HTML:
<div class="box">
  <p class="content">This text has a grey background.</p>
</div>

  • The box will be centered (margin-left + padding + width/2 = 50%)
  • The box content area will take up 20% of the screen and be grey in color.
  • The content will have blue padding around it that is 10% of the screen's width in all directions.
  • Changing the width of the screen will change the width of the box. 
Viewport Units
The viewport is the area of a web page that's visible to the user.
Viewport units set the width or height as a percent of the device's viewport.
  • vw: Sets the element width as a percent of the viewport width. 
    • ex: .halfScreenWidth { width: 50vw; }
  • vh: Sets the element width as a percent of the viewport height. 
    • ex .quarterScreenHeight { height: 25vh; }
Example
Set the class my-box-model width to 10% of the viewport width, and height to 25% of the viewport height.
.my-box-model {
  width: 10vw;
  height: 25vh;
}

Box ModelGo to video for this category

Ref: MDN_Guides:Box_model
Details
  • All elements, except those with display set to none, have a box around them.
  • The element content is surrounded on four sides by padding, a border, and margin.
  • For inline elements the default for each of those is 0px.
  • For most block elements the default value for each is also 0, but there is often a top and bottom margin.
  • Values can be length (e.g., px, rem, em) or percentage. 
  • Padding is affected by the element's background-color. Margin is not.

Width, height and Border Box

Ref: MDN:box-sizing
The width and height properties only affect the content area's size.
To have width and height include the padding and border widths (but not margin):
box-sizing: border-box;
Calculate total width and height. Set border-box for all elements.
  • You can set width and height properties in block elements, but they are ignored on inline elements.
  • Total width of an element = left-margin + left-border + left-padding + width + right-padding + right-border + right margin.
  • Total height of an element = top-margin + top-border + top padding + height + bottom padding + bottom border + bottom margin.
  • To simplify the math change the box-sizing property from the default (i.e., content-box) to border-box.
  • To set it for all elements, set it at the root element <html> then inherit it for all elements using the * universal element. Bootstrap uses this setting.
html {
  box-sizing: border-box;
}
*, *::before, *::after {
  box-sizing: inherit;
}

Min and max size
Ref: MDN:Sizing_items_in_CSS
min-width, max-width, min-height, max-height.
.box { min-height: 200px; } The element will be at least 200px high.
  • You can make images responsive by setting max-width to 100%. They will be displayed at the smaller of their intrinsic width (the image's actual width) or the screen width. 
.pic { max-width: 100%; } 

Padding

Ref: MDN:padding
Setting values with rem assists with accessibility and responsiveness.
Longhand: Set each side independently (top, right, bottom, left):
padding-left: .5rem; padding-right: .5rem;
Shorthand: padding: 0 .5rem;
Shorthand syntax
  • Default padding is 0px.
  • Ex: Set padding to 4px top and bottom, 8px right and left (assume base font-size: 16px):
padding-top: .25rem; padding-right: .5rem; padding-bottom: .25rem; padding-left: .5rem;
  • Shorthand syntax starts at the top and goes clockwise to right, bottom, then left:
padding: .25rem .5rem .25rem .5rem;
  • If the values for top and bottom are the same you only need to provide the top value. If right and left values are the same, then you only need to provide the right value:
padding: .25rem .5rem
  • If the values are the same for all four sides then you only need to provide one value.
padding: .5rem
  • Zero values do not need to specify the measurement unit. 
padding: 0;
Inline elements ignore vertical padding (top/bottom) of other inline elements on the same line.

Margin

Ref: MDN:margin
Setting values with rem assists with accessibility and responsiveness.
Longhand: Set each side independently (top, right, bottom, left):
margin-top: 1rem; margin-bottom: 1rem;
Shorthand: margin: 1rem 0;
Shorthand syntax
  • Default margin varies by element:
    • Inline elements: { margin: 0px }. 
    • Block elements:
      • body { margin: 8px; } Bootstrap resets body { margin: 0; }
      • div and layout elements main, nav, aside, footer, etc. { margin: 0px; }
      • p, pre { margin: 1em 0px; }. 
      • H1-h6 defaults to 0px for right-left margins. Each has it's own top-bottom margin.
  • Ex: Set margin to 16px top and bottom, 8px right and left (assume base font-size: 16px):
margin-top: 1rem; margin-right: .5rem; margin-bottom: 1rem; margin-left: .5rem;
  • Shorthand syntax starts at the top and goes clockwise to right, bottom, then left:
margin: 1rem .5rem 1rem .5rem;
  • If the values for top and bottom are the same you only need to provide the top value. If right and left values are the same, then you only need to provide the right value:
padding: .25rem .5rem
  • If the values are the same for all four sides then you only need to provide one value:
padding: .5rem
  • Zero values do not need to specify the measurement unit:
padding: 0;
Negative values: Negative margin is allowed, but not negative padding. 
#pic { margin: -2rem 0 0; } Moves element up overlapping the element above it.
Margin collapsing: Block elements on top of each other collapse the top and bottom margins, using the larger of the two. 
Example
<p>P1.</p>
<p>P2.</p>
<p style="margin-top: .5em">P3.</p>
  • Paragraph elements have default top and bottom margins of 1em. The browser will collapse the top and bottom margins. Instead of separating P1 and P2 by P1's bottom margin of 1em plus P2's top margin of 1em (totaling 2em), they are only separated by a collapsed 1em margin.
  • P2 has a default bottom margin of 1em, and P3 has a top margin set to .5em. They are collapsed, and the larger of the two, 1em, is used.

Border

Ref: MDN:border | MDN:border-style (shows results of different values)
Border properties:
  • Border-width: Default: 3px. For small border widths px are commonly used.
Ex: border-width: 1px;
  • Border-style: Default: none. Values: hidden, dotted, dashed, solid, double, groove, ridge, inset, outset.
Ex: border-style: double;
  • Border-color: Default: black. 
Ex: border-color: grey; 
border-color: currentColor; Sets border color to the element's (text) color.
  • border-width: 1px; border-style: solid; border-color: black;
    Shorthand: border: 1px solid black;
Shorthand (width style color): default: border: 3px none black;
Ex: border: 1px solid black;
Border sides: border-top, border-right, border-bottom, border-left.
Ex: border-top: 1px solid black; Sets one side, all 3 properties.
border-bottom-style: double; Sets one, one property.
Shorthand
  • Border, padding and margin allow shorthand to set the four sides.
  • Shorthand Order is clockwise: top, right, bottom, left:
    • border-style: solid dashed double dotted;
    • 1 value sets all four sides the same.
border-style: solid;
Equivalent to solid solid solid solid
    • 2 values use the first for top and bottom, the second for right and left.
border-style: solid none; 
Equivalent to solid none solid none
    • 3 values use the first for top, second for right and left, third for bottom.
border-style: solid none double;
Equivalent to solid none double none
Border-radius: MDN:border-radius
Individual corners: border-top-left, border-top-right, border-bottom-right, border-bottom-left.
Shorthand: border-radius: .25rem; Round the corners to 4px (when font-size: 16px)
Round one corner: border-top-right: .3rem;
Round horizontal at .4rem / vertical at .2rem: border-top-right: .4rem .2rem

Outline

Ref: MDN:outline
Like border, it draws a line around the element. And uses similar syntax:
outline: 1px dotted blue;
Unlike border it includes margin (if any), doesn't take up any space (i.e., overlaps the surrounding element), and you can't set individual sides. Can be useful in debugging.

Box-shadow

Ref: MDN:box-shadow
box-shadow: .5rem .25rem grey; X-axis (horizontal), y-axis (vertical), color.
box-shadow: 8px -4px red; X-axis: + right, - left. Y-axis: + down, - up.
box-shadow: 3px 1px 2px grey; Blur radius: blurs the shadow edges.
box-shadow: 3px 1px 0 1px grey; Spread radius: + expands, - shrinks.
box-shadow: inset 3px 1px grey; Inset places the shadow inside the box.
Details and example
  • box-shadow: none; removes any box shadow.
  • Optional inset keyword: Place this first to place the shadow inside the box. If missing the default is a drop shadow.
  • First two values are x-axis, y-axis.
  • Optional 3rd value, blur radius, default is 0 making the shadow edge sharp. Negative values are not allowed.
  • Optional 4th value, spread radius, default is 0 making the shadow the same size as the element.
  • Last value is color. Color values can be keywords, hex values, rgb values.

  • Box-shadow takes on the same rounded corners as the element, if any.
  • Example:
HTML:
<div class="box">This is a box</div>

CSS:
.box {
  padding: .5rem;
  border: 1px solid black;
  margin: .5rem;
  box-shadow: 3px 1px 2px 1px grey;
}

Bootstrap

Ref: getbootstrap.com/docs > click Utilities: spacing
m margin | p padding
t top | b bottom | s start/left | e end/right | x left & right | y top & bottom
1 .25rem | 2 .5rem | 3 1rem | 4 1.5rem | 5 3rem
auto - for classes that set the margin to auto
Examples
class="m-1" margin: .25rem;
class="p-2" padding: .5rem;
class="mt-3" margin-top: 1rem;
class="mb-3" margin-bottom: 1rem;
class="my-3" margin-top: 1rem; margin-bottom: 1rem;
class="ms-4" margin-left: 1.5rem;
class="me-4" margin-right: 1.5rem;
class="mx-5" margin-left: 3rem; margin-right: 3rem;

FlexBox

Ref: MDN_Guides:Flexbox | w3schools flexbox
Browser Support (Since 2013-15) caniuse.com/#search=flexbox

Terms

The Flexible Box Module (Flexbox):  A one-dimensional layout model to control space distribution and alignment among items.
Flex container: The parent element that has display: flex set on it.
Flex items: Direct child elements of a flex container automatically become flex items.
Main axis: Direction the flex items are being laid out by the flex-direction. Default is row. Starts/ends with: main-start, main-end.
Cross axis: Runs perpendicular to the main axis. Starts/ends with: cross-start, cross-end.

Example Flexbox Template

Example template
<!DOCTYPE html>
<html>
<head>
<title>flexbox</title>
<style>
/* Delete the default flexbox properties you don't intend to change */
.flex-container {
  max-width: 960px;
  border: 1px solid black;
  background-color: navy;
  /* Set height or min-height to see impact of align-content */
  min-height: auto; /* 400px */
  display: flex;
  /* Flex properties set to their defaults: */
  flex-direction: row; /* row, column, row-reverse, column-reverse */
  flex-wrap: nowrap; /* nowrap, wrap, wrap-reverse */
  justify-content: flex-start; /* horizontal alignment: flex-start, flex-end, center, space-between, space-around, space-evenly */
  align-content: stretch; /* vertical alignment (ignored if height not fixed): normal or stretch, flex-start, flex-end, center, space-between, space-around, space-evenly */
  align-items: stretch; /* vertical alignment of individual items: stretch, flex-start, flex-end, center */
}
.flex-item {
  background-color: aqua;
  border: 1px solid black;  
  padding: .5rem;
  /* Size properties set to their defaults: */
  margin: 0; /* To set fixed margin widths */
  width: auto; /* Set fixed width, min-width, max-width */
  height: auto; /* Set fixed height, min-height, max-height */
  /* Flex properties set to their defaults: */
  flex: initial; /* initial auto, none, 1 */
  align-self: stretch; /* normal or stretch, flex-start, flex-end, center */
}
#fi3 {
  /* Flex properties set to their defaults: */
  flex: initial; /* initial, auto, none, x */
  align-self: stretch; /* normal or stretch, flex-start, flex-end, center */
  order: 0; /* 0, -x (first), x (last) */
}
</style>
</head>
<body>
<section id="container1" class="flex-container">
  <div id="fi1" class="flex-item">Flex Item 1</div>
  <div id="fi2" class="flex-item">Item 2</div>
  <div id="fi3" class="flex-item">Flex Item Number 3</div>
  <div id="fi4" class="flex-item">I4</div>
  <div id="fi5" class="flex-item">Flex Item Number 5 is the longest item.</div>
</section>
</body>
</html>

Flex Container Properties

Properties and default values:
.flex-container { 
  display: flex; /* use flex */
  flex-direction: row; /* column, row-reverse, column-reverse */
  flex-wrap: nowrap; /* wrap, wrap-reverse */
  justify-content: flex-start; /* horizontal alignment: flex-end, center, space-around, space-evenly */
  align-items: stretch; /* vertical alignment: flex-start, flex-end, center */
}
Summary
  • display: flex; Use flex.
  • flex-direction: row (default), row-reverse, column, column-reverse.
  • flex-wrap: nowrap (default), wrap, wrap-reverse.
  • flex-flow: Shorthand property for setting both the flex-direction and flex-wrap properties.
  • justify-content: horizontal alignment: flex-start (default), flex-end, center, space-around (spaces each element evenly), space between (same as space around but is flush with each end).
  • align-content: vertical alignment of multiple lines when height is fixed: stretch (default), flex-start, flex-end, center, space-around, space-between.
  • align-items: vertical alignment: stretch (default), flex-start, flex-end, center, baseline (where letters sit).
Display: flex;
To use flex, set the parent element display property to flex:
display: flex;
Flex-direction
Ref: MDN:flex-direction
flex-direction: row; Row (the default) aligns items horizontally. 
    • column (the normal flow direction) aligns items vertically. 
    • row-reverse and column-reverse reverse the order.
Flex-wrap
Ref: MDN:flex-wrap
flex-wrap: wrap; The item elements wrap inside the parent element.
    • nowrap Default. The item elements overflow if not enough room.
    • wrap-reverse Wraps starting at the end row going up.
Flex-flow shorthand
flex-flow: column wrap; Shorthand for flex-direction, flex-wrap.
Justify-content
Ref: MDN:justify-content
Distribute space between and around flex items along the flex container's main axis.
Container Ex: flex-direction: row. Justify items in relation to its horizontal axis
justify-content: flex-start; Start items from flex container's start (e.g., left side).
    • flex-end Start items from flex container's end (e.g., right side).
    • center Places items in center of flex container.
    • space-between First/last items flush with start/end, even spaces between.
    • space-evenly Equal spaces between items including before/after first/last.
    • space-around Like space-evenly, but uses half equal space before/after first/last.
To set specific space between items use the margin property directly on the items.
Align-content
Ref: MDN:align-content
Often not used, unless cross-axis (e.g., height) is fixed. 
Distribute space between and around flex items along the flex container's cross axis.
Container Ex: Flex-direction: row with fixed height. Align items along its vertical axis:
align-content: normal; Default value. Same effect as stretch.
    • stretch Stretches the items so they fill the whole container's height.
    • flex-start Aligns items vertically against the top of the container.
    • flex-end Aligns items vertically against the bottom.
    • center Aligns items vertically in the center of the container.
    • space-between First/last rows flush with top/end, even space(s) between.
    • space-evenly Equal spaces before, between, and after rows.
    • space-around Like space-evenly. Top/bottom spaces are half height.
To set specific space between items use the margin property directly on the items.
Align-items
Ref: MDN:align-items
Sets the cross-axis alignment of all the direct flex items. 
In effect sets each flex item's align-self value as a group.
align-items: stretch; Default. Each element stretches to the length of the element's cross-axis.
    • flex-start Each item aligns with the start of the parent element's cross-axis.
    • flex-end Each item aligns with the end of the parent element's cross axis.
    • center Each item aligns to the center of the parent element's cross-axis.

Flex Item Properties

<div id="flex-item-1" class="flex-item">Item 1</div>
Use class to style all the flex items: 
.flex-item { flex: 1; }
Use id to style a single flex item:
#flex-item-3 { flex: 2; align-self: flex-start }
Or use pseudo-classes (only works with tag names not ids/classes).
section > div:first-child { flex: 2; } :last-child, :nth-child(x), :nth-last-child(x)
Flex (shorthand property)
Ref: MDN:flex
1 Keyword Value: 
flex: initial; Default. Sized by its width, height properties. Shrinks to fit container.
    • auto Sized by its width, height properties. Grows and shrinks to fit container.
    • none Sized by its width, height properties. Size is fixed (won't shrink/grow).
1 Num Value: Proportion of available space along the main axis each item will take up.
flex: 1; If there are 3 items with flex: 1, then each takes up 1/3 of the row.
  • 2 items are flex: 1, one is flex: 2 they take up 1/4, 1/4, 2/4 respectively.
2 Values: 1st value is same as above. Second is the initial width.
flex: 1 200px;
Align-self
Ref: MDN:align-self
Sets the cross-axis alignment of the item. Overrides align-items.
align-self: stretch; Default. Stretches to the length of the element's cross-axis.
  • flex-start Aligns with the start of the parent element's cross-axis.
  • flex-end Aligns with the end of the parent element's cross axis.
  • center Aligns to the center of the parent element's cross-axis.
Order
Changes the order of a flex item. Default is 0.
order: 1; Places item after all items with default order 0.
    • -1 Places item before all items with default order 0.
    • 7 Places item after all items below 7.

GridGo to video for this category

Ref: MDN_Guides:Grids 
Browser support since Mar 2017 (Edge: Oct 2017). caniuse.com/#search=grid

Display: grid

To use a grid layout, set the parent element display property to grid:
HTML: <div class="container">Page layout here</div>
CSS: .container { display: grid; }

Grid-template-columns  

Ref: MDN:grid-template-columns
  • List width of each column: List each column's width units.
grid-template-columns: 500px 250px 250px; 3 columns. Width of each column in px.
grid-template-columns: 50% 25% 25%; 3 columns. Width of each column in % of screen.
grid-template-columns: 2fr 1fr 1fr; 3 cols. Width fraction of remaining screen (2/4ths, 1/4th, 1/4th)
  • Repeat value: If width is the same use repeat(cols, width); 
grid-template-columns: repeat(4, 250px); 
grid-template-columns: repeat(4, 25%); 
grid-template-columns: repeat(4, 1fr); 
  • As many columns as will fit: repeat(auto-fill, width)
grid-template-columns: repeat(auto-fill, 300px); As many 300px cols as fits.
  • Min/max values: minmax(min width, max width)
3 cols: 1/6, 4/6, and 1/6 of screen. Won't shrink below 600px (150px+300px+150px).
grid-template-columns: minmax(150px, 1fr) minmax(300px, 4fr) minmax(150px, 1fr);
3 cols 1/3 of screen. Min width 200px. Won't shrink below 600px wide (200px x 3).
grid-template-columns: repeat(3, minmax(200px, 1fr));

Gap/Grid-gap

Ref: MDN:gap
Add a gutter between grid cells. The property name has changed from grid-gap to gap. Use both for wider support.
grid-gap: 10px; gap: 10px;
If column and row gaps differ, use two values: gap: row column
grid-gap: 1rem .5rem; gap: 1rem .5rem;
Apply only column or only row gaps:
grid-row-gap: 20px; row-gap: 20px;
grid-column-gap: 10px; column-gap: 10px;

Grid-auto-rows

Ref: MDN:grid-auto-rows
Optionally, apply height to rows. Default: auto adjusts to height of content.
grid-auto-rows: 100px; Sets all rows to 100px height.
grid-auto-rows: minmax(100px, auto); Adjusts to height of content, with min of 100px

Grid-row, grid-column

Ref: MDN:grid-row | MDN:grid-column
grid-row: 1; grid-column: 1; Places element in the first row, first column.
grid-row: 2 / 4; grid-column: 3; Places element down column 3, spans rows 2-3;
grid-row: 5; grid-column: 1 / 3; Places element on 5th row, spans cols 1-2.
grid-row: 5; grid-column: 1 / -1; -1 means the last col. -2, second from last.
grid-row: 5; grid-column: 1 / span 3; Starts on col 1 and spans 3 cols to right.
grid-row: 5; grid-column: 2 / span 2; Starts on col 2 and spans 2 cols to right.

Bootstrap

Ref: getbootstrap.com/docs/5.2/layout/grid
Note: Bootstrap uses CSS flexbox for its default grid.
Set a row class. Nest elements using col-* class. There are 12 columns per row. 
<div class="row">
  <div class="col">No breakpoint. Columns auto calculated</div> <div class="col-md">Md breakpoint 768px. Cols auto calculated</div> <div class="col-md-3">Md breakpoint 768px. 3 cols wide (of 12)</div>
</div>
Responsive breakpoints:
Sizexssmmdlgxlxxl
Class prefix.col-.col-sm-.col-md-.col-lg-.col.xl-.col-xxl-
Breakpoint:<576px≥576px≥768px≥992px≥1200px≥1400px
Examples
  • Three columns of equal width. No breakpoint.
<div class="row">
  <div class="col">C1 Content</div>
  <div class="col">C2 Content</div>
  <div class="col">C3 Content</div>
</div>

  • Three columns of different width. Md breakpoint.
<div class="row">
  <div class="col-md-6">C1 Content</div>
  <div class="col-md-3">C2 Content</div>
  <div class="col-md-3">C3 Content</div>
</div>

Other Commonly Used Properties

Ref: MDN:CSS properties index

Display

Ref: MDN:display
All elements have a default display property that specifies its display behavior.
  • Not displayed elements: head, meta, link, title.
display: none; Element is not displayed.
  • Block Elements: div, body, h1-h6, p, li, form, hr, nav, main, footer, section.
display: block; Block elements take up the full width available (of the parent element) and have a line break before and after them.
  • Inline elements: span, b, strong, i, em, u, a, small, img, label.
display: inline; Only take up as much room as needed and do not add line breaks before and after the element.
Unlike blocks, except for img tags, you cannot set width or height values
You also cannot set padding and margin on the top or bottom of an inline element.
  • Inline-block elements: button, input, textarea, select
display: inline-block; Like inline but you can set width and height values and padding/margin on the top and bottom.

Visibility

visibility: hidden; Element isn't shown, but unlike display: none, it still takes up space on the page. Default: visible.

Overflow and Scroll

Ref: MDN:overflow
If you set a height dimension the content might exceed the height. it and cause visible overflow. 
Overflow: visible; Default value. Excess text visibly overflows on top of the element below. Messy.
    • hidden Excess text is cropped. Usually not the best option.
    • scroll Displays a scrollbar to the right, which can be used if there is overflow.
    • auto Displays a scrollbar to the right only if there is overflow.
Scroll from the bottom.
You may want to scroll from the bottom. For instance in a chat application you may have a fixed height screen with the most recent messages at the bottom, along with an input box to respond. As new messages come in, older messages scroll up and out of sight. 
.scroll {
  max-height: 150px;  /*or height*/
  overflow: auto;
  display: flex;
  flex-direction: column-reverse;
}
  • On the back end you will need to reverse the order of the messages:
Message.all.reverse

Float

Ref: MDN:float
float: left; Values: none, left, right;
Places element to the left or right of its container. Text or other elements wrap around it. 

Position

Ref: MDN:position | MDN:z-index
position: relative; top: 1rem; left: 1rem; Default: static (the normal position), relative, absolute, fixed, sticky.
  • Relative: Offset relative to itself. The normal space is still reserved for the element, even though the display of it is moved.
  • Absolute: Removed from the normal document flow. No space is reserved for it so it just overlaps other elements. Positioned (with top/bottom, left/right) relative to its closest positioned ancestor element.
  • Fixed: Like fixed, except it is positioned relative to the initial containing block of the viewport. Stay fixed with the screen (i.e., does not scroll). Useful for fixing nav bars, footers, or background images.
  • Sticky: Relatively positioned until the user scrolls to a specified threshold, then it becomes fixed. When the user scrolls past the parent element it is relatively positioned again (and scrolled out of view).
    • Safari requires a prefix of webkit- so you need both: position: sticky; position: webkit-sticky;
Top, bottom, left, right: Position/offset the element using these properties. 
  • These properties are ignored with position: static.
Z-index: Sets which overlapping element is on top.
position: absolute; bottom: 30px; z-index: 1; Default: auto (the normal flow). Values: integers.
  • Default: auto (the normal flow). The last element in the HTML code goes on top.
  • Positive integers stack on top of an element with no z-index specified, negative underneath. 
  • Multiple layered elements stack highest to lowest integer.
Example - put text over an image.
  • Example:
    • Below is an image inside a figure element. 
    • We want to add a caption that overlaps the top of the image. 
    • Add position: relative and top: 40px style rules to push the figcaption element down 40px from the top.
CSS:
.pic { 
  width: 400px; /* same as the image's intrinsic width */
  height: 300px; /* same as the image's intrinsic height */
  max-width: 100%;
}
.figure {
  float:left;
  border: 1px solid black;
  border-radius: .25rem;
}
.figcaption { 
  text-align: center;
  max-width: 50%;
  margin-left: auto;
  margin-right: auto;
  background-color: black; 
  color: white; 
  font-size: 1.5rem;
  position: relative;
  top: 40px;
}
HTML:
<figure class="figure">
  <figcaption class="figcaption">Angry cat</figcaption>   
  <img src="angry-cat.png" alt="Angry cat" class="pic">
</figure>

Cursor

Ref: MDN:cursor
Changes the look of the cursor when hovering over the element. Defaults:
  • cursor: default; diagonally pointed arrow.
  • cursor: text; Shaped like an I beam. Used on elements that normally contain text (p, h1-h6, li, table, div, form inputs)
  • cursor: pointer; pointing hand. Used on links.
Other options: none, grab, grabbing, move, not-allowed (circle slash), crosshair, wait (hourglass or spinner), help (question mark), and more. 

initial/inherit/unset/revert

initial: Applies the initial (or default) value of a property to an element.
selector { prop: initial } 
inherit: Inherits from parent elem.
selector { prop: inherit }
unset: Resets a property to its inherited value if the property naturally inherits from its parent, and to its initial value if not.
selector { prop: unset }
revert: Reverts to the default for an element.
selector { prop: revert }