Cascading Style Sheets (CSS)

Cascading Style Sheets (CSS) is a style sheet language used to specify the presentation and styling of documents written in markup languages such as HTML or XML. CSS uses rules to define how the content of HTML elements should appear.

The term "cascading" refers to the way these rules can be layered on top of one another. When two or more rules apply to the same element, it is important to understand which rules takes precedence.

div {
  margin: 1rem;
  padding: 1rem;
}

p {
  color: blue;
}

CSS Syntax

Understanding CSS Code

A CSS rule contains two parts: a selector and a declaration.

  • Selector - Indicates which element the rule applies to. The same rule can apply to more than one element if you separate the element names with commas. A space between selectors means "select elements inside other elements."
  • Declaration - Indicates how the elements referred to in the selector should be styled. Declarations are everything between the two curly brackets, and each declaration is split into two parts - a property and a value. Declarations are separated by a colon.
    • Property - Indicates the aspects of the element you want to change.
    • Value - Specify the settings you want to use for the chosen properties.

There are two rules that apply to CSS rules:

  • Last Rule - If the two selectors are identical, the latter of the two will take precedence.
  • Specificity - If one selector is more specific than the others, the more specific rule will take precedence over more general ones.
selector {
  property: value; /* This is one declaration */
  property: value; /* This is another declaration */
}
/* For all paragraph text in the HTML file, the font-family will be Arial */

p {
  font-family: Arial;
}

/* For all h1, h2, and h3 headers in the HTML file, the font-family will be Arial and the color will be yellow */

h1, h2, h3 {
  font-family: Arial;
  color: yellow;
}

/* Inheritance and Important */

body {
  padding: 10px;
}

h1.page {
  font-family: inherit;
  color: yellow !important;
}

Adding CSS to a File

Linking to an External CSS File

<head>
  <link rel="stylesheet" href="css/typography.css" type="text/css" />
  <link rel="stylesheet" href="css/tables.css" type="text/css" />
</head>

Placing the CSS in the Header of an HTML File

<head>
  <style type="text/css">
    p {
      color: blue;
    }
  </style>
</head>

Placing the CSS Inside an Element

<p style="color:blue;">

Using @import

@import url("typography.css");
@import url("tables.css");

CSS Selectors

Different Types of CSS Selectors

  • Universal Selector - Applies to all elements in a document.
  • Type Selector - Matches element names.
  • Class Selector - Matches an element whose class attribute has a value that matches the one specified after the period symbol.
  • ID Selector - Matches an element whose id attribute has a value that matches the one specified after the pound or hash symbol.
  • Child Selector - Matches an element that is a direct child of another.
  • Descendent Selector - Matches an element that is a descendent of another specified element (not just a direct child of that element).
  • Adjacent Sibling Selector - Matches an element that is the next sibling of another.
  • General Sibling Selector - Matches an element that is a sibling of another, although it does not have to be the directly preceding element.
/* Universal Selector */

* {
  color: blue;
}

/* Type Selector */

h1, h2, h3 { }

/* Class Selector */

p.note { }

/* ID Selector */

h1#introduction { }

/* Child Selector */

li > a { }

/* Descendent Selector */

p a { }

/* Adjacent Sibling Selector */

h1 + p { }

/* General Sibling Selector */

h1 - p { }

Sub-Classes of Selectors

Break up the CSS styles into individual classes, and refer to both of those classes in the HTML.

<div class="message referral">
div.message {
  width: 200px;
}

div.referral {
  background-color: green;
}

/* This applies styles to divs that has BOTH classes message and referral at the same time, narrowed down to divs */

div.message.referral {
  background-color: red;
}

Attribute Selectors

  • Existence - Matches a specific attribute (whatever its value).
  • Equality - Matches a specific attribute with a specific value.
  • Space - Matches a specific attribute whose value appears in a space-separated list of words.
  • Prefix - Matches a specific attribute whose value begins with a specific string.
  • Substring - Matches a specific attribute whose value contains a specific substring.
  • Suffix - Matches a specific attribute whose value ends with a specific string.
/* Existence */

p[class]

/* Equality */

p[class="dog"]

/* Space */

p[class~="dog"]

/* Prefix */

p[attr^"d"]

/* Substring */

p[attr*"do"]

/* Sufix */

p[attr$"g"]

Creating CSS Variables

:root {
  --blue: rgb(0, 106, 255);
  --light-blue: rgb(156, 186, 227);
}

.button {
  background-color: var(--blue);
}

CSS Styles

Color

/* Foreground Color */

p {
  color: DarkCyan;
}

h2 {
  color: #ee3e80;
}

p {
  color: rgb(100, 100, 90);
}

/* Background Color */

p {
  background-color: DarkCyan;
}

h2 {
  background-color: #ee3e80;
}

p {
  background-color: rgb(100, 100, 90);
}

/* Opacity and RGBA w/ Fallbacks */

p {
  background-color: rgb(0, 0, 0);
  opacity: 0.5;
}

p {
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.5);
}

/* HSL (Hue, Saturation, Lightness) w/ Fallbacks */

body {
  background-color: #C8C8C8;
  background-color: hsl(360, 0%, 78%);
}

p {
  background-color: #ffffff;
  background-color: hsla(0, 100%, 100%, 0.5);
}

Text

/* Specifying Typefaces */

body {
  font-family: "Courier New", Verdana, sans-serif;
}

p {
  font-family: Georgia, Times, serif;
}

/* Size of Type */

body {
  font-size: 12px;
}

h1 {
  font-size: 200%;
}

h2 {
  font-size: 1.3em;
}

/* More Font Choices */

@font-face {
  font-family: 'ChunkFiveRegular';
  src: url('fonts/chunkfive.eot');
}

h1 {
  font-family: ChunkFiveRegular, Georgia, serif;
}

@font-face {
  font-family: 'ChunkFiveRegular';
  src:  url('fonts/chunkfive.eot');
  src:  url('fonts/chunkfive.eot?iefix') format('embedded-opentype'),
        url('fonts/chunkfive.woff') format('woff'),
        url('fonts/chunkfive.ttf') format('truetype'),
        url('fonts/chunkfive.svg#ChunkFiveRegular') format('svg');
}

/* Bold */

p {
  font-weight: normal;
}

h1 {
  font-weight: bold;
}

/* Italic */

body {
  font-style: normal;
}

p {
  font-style: italic;
}

h1 {
  font-style: oblique;
}

/* Uppercase and Lowercase */

h1 {
  text-transform: uppercase;
}

h2 {
  text-transform: lowercase;
}

p.credits {
  text-transform: capitalize;
}

/* Underline and Strike */

p.credits {
  text-decoration: underline;
}

a {
  text-decoration: none;
}

h1 {
  text-decoration: overline;
}

h2 {
  text-decoration: line-through;
}

a.blinking {
  text-decoration: blink;
}

/* Leading */

p {
  line-height: 1.4em;
}

/* Letter & Word Spacing - Kerning */

h1, h2 {
  letter-spacing: 0.2em;
  word-spacing: 1em;
}

/* Alignment */

h1 {
  text-align: center;
}

/* Vertical Alignment */

h1 {
  vertical-align: baseline;
}

/* Indenting Text */

h1 {
  text-indent: -9999px;
}

p {
  text-indent: 20px;
}

/* Drop Shadow */

p {
  text-shadow: 1px 1px 0px #000000;
}

/* Pseudo Elements and Pseudo Classes */

p.intro:first-letter {
  font-size: 200%;
}

p.intro:first-line {
  font-weight: bold;
}

/* Styling Links */

a:link {
  color: blue;
}

a:visited {
  color: red;
}

a:hover {
  color: green;
}

a:focus {
  color: pink;
}

a:active {
  color: yellow;
}

/* Removing Highlighting/Selection from User */

div {
  user-select: none;
}

Containers

/* Box Dimensions */

div {
  height: 300px;
  width: 200px;
  background-color: grey;
}

/* Limiting Height */

div {
  min-height: 200px;
  max-height: 500px;
  background-color: grey;
}

/* Limiting Width */

div {
  min-width: 200px;
  max-width: 500px;
  background-color: grey;
}

/* Overflowing Content */

p {
  overflow: hidden; /* hidden or scroll */
}

/* Border, Margin, and Padding */

div {
  margin: 10px;
  border: 2px;
  padding: 20px;
}

/* Border Width */

div {
  border-width: 2px; /* thin, medium, thick, #px */
}

div {
  border-top-width: 2px;
  border-right-width: 3px;
  border-bottom-width: 4px;
  border-left-width: 5px;
}

div {
  border-width: 2px 1px 1px 2px; /* top, right, bottom, left */
}

/* Border Style */

div {
  border-style: solid; /* solid, dotted, dashed, double, groove, ridge, inset, outset, hidden/none */
}

div {
  border-top-style: solid;
  border-right-style: dotted;
  border-bottom-style: dashed;
  border-left-style: double;
}

div {
  border-style: solid dashed solid dashed;
}

/* Border Color */

div {
  border-color: blue;
}

div {
  border-top-color: blue;
  border-right-color: red;
  border-bottom-color: green;
  border-left-color: yellow;
}

/* Border Shorthand */

div {
  border: 2px solid black;
}

/* Padding */

div {
  padding: 10px;
}

div {
  padding-top: 10px;
  padding-right: 2px;
  padding-bottom: 4px;
  padding-left: 8px;
}

div {
  padding: 10px 5px 3px 1px;
}

div {
  padding: 20px 10px; /* top/bottom left/right */
}

/* Margin */

div {
  margin: 10px;
}

div {
  margin-top: 10px;
  margin-right: 2px;
  margin-bottom: 4px;
  margin-left: 8px;
}

div {
  margin: 10px 5px 3px 1px;
}

div {
  margin: 20px 10px; /* top/bottom left/right */
}

/* Centering Content (On Page or Inside Another Box) */

/* Width of the inner box needs to be smaller than the outer box */

div {
  margin: 20px auto; /* auto essentially means equal */
}

div {
  margin: 20px auto 20px auto;
}

/* Change Inline/Block */

li {
  display: inline; /* inline, block, inline-block, none */
}

/* Hiding Boxes */

li {
  visibility: hidden; /* hidden, visible */
}

/* Box Shadow */

p {
  box-shadow: -5px -5px black;
}

p {
  box-shadow: inset 5px 5px 5px blue; /* horizontal offset, vertical offset, blur distance (blur or solid), spread of shadow (distance) */
}

/* Rounded Corners  */

p {
  border-radius: 10px;
}

p {
  border-top-right-radius: 10px;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 10px;
  border-top-left-radius: 5px;
}

p {
  border-radius: 10px 5px 10px 5px;
}

Lists

/* Bullet Point Styles */

ul {
  list-style-type: disc; /* none, disc, circle, square */
}

ol {
  list-style-type: square; /* decimal, decimal-leading-zero, lower-alpha, upper-alpha, lower-roman, upper-roman */
}

/* Bullet Point Images */

ul {
  list-style-image: url("images/star.png");
}

/* Positioning the Marker */

ul {
  list-style-position: outside; /* outside or inside */
}

/* List Shorthand */

ul {
  list-style: inside circle;
}

Tables

/* Table Properties */

table {
  width: 600px;
}

th, td {
  padding: 7px 10px 10px 10px;
}

th {
  text-transform: uppercase;
  letter-spacing: 0.1em;
  font-size: 90%;
  border-bottom: 2px solid darkblue;
  border-top: 1px solid red;
  text-align: left;
}

tr.even {
  background-color: blue;
}

tr:hover {
  background-color: grey;
}

/* Border on Empty Cells */

table.one {
  empty-cells: show; /* show, hide, or inherit */
}

/* Gaps Between Cells */

table.one {
  border-spacing: 5px 15px; /* horizontal and vertical */
}

table.two {
  border-collapse: collapse; /* collapse or separate */
}

Forms

/* Styling Text Inputs */

input {
  font-size: 14px;
  color: red;
  background-color: gray;
  border: 1px solid black;
  border-radius:;
}

input:focus, input:hover {
  background-color: lightblue;
  border: 1px solid red;
}

input#email {
  background-image: url("images/email.png");
}

/* Styling Submit Buttons */

input#submit {
  color: red;
  text-shadow: 0px 1px 1px white;
  border-bottom: 2px solid green;
  background-color: cyan;
}

input#submit:hover {
  color: white;
  background-color: blue;
}

/* Styling Fieldsets and Legends */

fieldset {
  width: 350px;
  border: 1px solid blue;
  border-radius: 10px;
  padding: 20px;
  text-align: right;
}

legend {
  background-color: red;
  border: 1px solid black;
  border-radius: 10px;
  padding: 10px 20px;
  text-align: left;
  text-transform: uppercase;
}

/* Aligning Form Controls */

/*
  1. Place every input in a div so it will be on a new line
  2. Use the float property to move the titles to the left and align them
*/

div {
  border-bottom: 1px solid black;
  margin: 10px;
  padding-bottom: 10px;
  width: 260px;
}

.title {
  float: left;
  width: 100px;
  text-align: right;
  padding-right: 10px;
}

.submit {
  text-align: right;
}

/* Cursor Styles */

a {
  cursor: auto; /* auto, crosshair, default, pointer, move, text, wait, help, url("images/image.png") */
}

Images

/* Controlling Image Sizes */

img.large {
  width: 500px;
  height: 500px;
}

img.small {
  width: 150px;
  height: 150px;
}

/* Aligning Images */

img.align_left {
  float: left;
  margin-right: 10px;
}

img.align_right {
  float: right;
  margin-left: 10px;
}

/* Centering Images */

img.align_center {
  display: block;
  margin: 0px auto;
}

/* Background Images */

body {
  background-image: url("images/pattern.gif");
}

p {
  background-image: url("images/pattern.gif");
}

/* Repeating Images */

body {
  background-image: url("images/header.gif");
  background-repeat: repeat-x; /* repeat, repeat-x, repeat-y, no-repeat */
}

body {
  background-image: url("images/tulip.gif");
  background-repeat: no-repeat;
  background-attachment: fixed; /* fixed or scroll */
}

/* Background Position */

body {
  background-image: url("images/tulip.gif");
  background-repeat: no-repeat;
  background-position: center top; /* left/center/right top/center/bottom ex. left top, right center */
}

/* Shorthand */

body {
  background: #ffffff url("images/tulip.gif") no-repeat top right;
}

Positioning

Types of Positioning

There are five possible values for the position property.

When using anything other than static, you can use top, bottom, left, right, and z-index to position the element exactly where you want it to be.

  • Static
  • Relative
  • Absolute
  • Fixed
  • Sticky

Static (Default)

There will be no effect on the element's positioning.

.element {
  position: static;
}

Relative

Change the position of the element relative to where it would normally be.

.element {
  position: relative;
  top: 0;
  right: 0;
}

Absolute

The element will be positioned relative to its nearest ancestor that has a specified position. If the parent element doesn't have position: relative;, the child element will be positioned relative to the body.

.parent {
  position: relative;
  top: 0;
  right: 0;
}
.child {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 1;
}

Fixed

The element will be positioned fixed relative to the window and will follow along on a scrolling website. Top, bottom, left, right work in relation to the entire window.

.element {
  position: fixed;
  top: 0;
  right: 0;
}
.element {
  position: fixed;
  top: 50%;
  left: 50%;
  translate: -50% -50%;
}

Sticky

Behaves just like a normal element, but when inside a scrollable website or container, the moment the element hits a specified position, it sticks to that position.

.element {
  position: sticky;
  top: 100px;
}

Different Types of Positioning

Building Blocks - CSS treats each HTML element as if it is in its own box. This box will either be a block-level box or an inline box.

  • Block-Level Box - Block-level boxes start on a new line and act as the main building blocks of any layout.
  • Inline Box - Inline boxes flow between surrounding text.

Containing Elements - If one block-level element sits inside another block-level element then the outer box is known as the "containing" or "parent" element. It is common to group a number of elements together inside a <div> element.

  • Normal Flow - Every block-level element appears on a new line, causing each item to appear lower down the page than the previous one. Boxes will not appear next to each other.
  • Relative Positioning - Moves the element from the normal position to the top, right, bottom, or left of where it would have been placed. Does not affect surrounding elements in normal flow.
  • Absolute Positioning - Positions the element in relation to its containing element. The box is taken out of normal flow and does not affect the position of other elements on the page. The box offset properties specific where the element should appear in relation to its containing element. Absolutely positioned elements moved as users scroll up and down the page.
  • Fixed Positioning - A form of absolute positioning that positions the element in relation to the browser window as opposed to containing elements. Does not affect the position of surrounding elements and they do not move as users scroll up and down the page.
  • Z-Index - If any elements are overlapping, this allows you to bring them closer to the user or push them back.
  • Float - Allows you to take an element in normal positioning and place it as far to the left or right of the containing element as possible (requires a defined width).
  • Clear - No element within the same containing element should touch the left or right hand sides of a box.
/* Normal Flow */

p {
  position: static;
}

/* Relative Positioning */

p {
  position: relative;
  top: 10px;
  bottom: 0px;
  left: 100px;
  right: 0px;
}

/* Absolute Positioning */

p {
  position: absolute;
  top: 0px;
  bottom: 0px;
  left: 500px;
  right: 0px;
  width: 450px;
}

/* Fixed Positioning */

p {
  position: fixed;
  top: 0px;
  bottom: 0px;
  left: 0px;
  right: 0px;
  padding: 20px;
  width: 100%;
}

/* Sticky Positioning */



/* Overlapping Elements */

h1 {
  position: fixed;
  z-index: 10;
}

/* Floating Elements */

blockquote {
  float: right;
  width: 300px;
}

/* Side-by-Side Elements */

body {
  width: 750px;
}

p {
  width: 230px;
  float: left;
  margin: 5px;
  padding: 5px;
  background-color: lightblue;
}

.clear {
  clear: left; /* left, right, both, none */
}

/* Parents of Floated Elements */

div {
  border: 1px solid black;
  overflow: auto;
  width: 100%;
}

/* Creating Multi-Column Layouts */

div.column1of2 {
  float: left;
  width: 600px;
  margin: 10px;
}

div.column2of2 {
  float: left;
  width: 300px;
  margin: 10px;
}

div.column {
  width: 300px;
  float: left;
  margin: 10px;
}

Flexbox and Grid

Flexible Box Layout (Flexbox)

CSS Flexbox, short for "Flexible Box Layout" is a one-dimensional layout model used for designing responsive layouts and distributing space among items within a container using rows or columns.

Flexbox works by designating a parent as a flex container and its children as flex items, then applying properties to control direction, spacing, and alignment on the main and cross axes.

display: flex;

Direction

flex-direction: row;

flex-direction: column;

Spacing

gap: 1rem;

Wrapping Items

flex-wrap: wrap;

Aligning Items (Main Axis)

justify-content: center;

justify-content: space-between;

Aligning Items (Cross Axis)

align-items: center;

align-items: stretch;

Grid Layout (Grid)

CSS Grid is a two-dimensional layout model used for designing responsive layouts and distributing space among items within a container using rows and columns.

Grid works by designating a parent as a grid container and its children as grid items, then applying properties to control spacing.

display: grid;
.parent {
  display: grid;
  grid-template-columns: repeat(auto-fit, 300px);
  gap: 1rem;
  justify-content:center;
  width: 100%;
}

.child {
  width: 300px;
  height: 400px;
}

Transitions & Transforms

Note: You can't add CSS transitions when deleting or adding an element to the DOM. It must be a class-toggle.

Basic Transitions

Transitions control how a change happens over time

  • ease
  • ease-in
  • ease-out
  • ease-in-out
.parent {
  transition:
    opacity 0.3s ease-in-out;
}

.child.open {
  opacity: 1;
}

.child.closed {
  opacity: 0;
}

Basic Transforms

Transforms change how the element looks in space (position, size, rotation, skew).

  • transform: translateX(100px)
  • transform: rotate(360deg)
  • transform: rotateX(360deg)
  • transform: rotateY(360deg)
  • transform: scaleX(1.5)
  • transform: scale(1.5)
  • transform: skew(30deg 100deg)
.parent {
 transition:
  opacity 0.4s ease-in-out,
  transform 0.4s ease-in-out;
}

.child.open {
  opacity: 1;
  transform: rotate(0deg);
}

.child.closed {
  opacity: 0;
  transform: rotate(360deg);
}

Toggling Visibility

Different Ways to Toggle Visibility

Opacity

Opacity makes the element fully transparent. It still takes up space and can receive clicks, focus, and events.

.element {
  opacity: 0;
}

.element {
  opacity: 1;
}

Visibility

Visibility makes the element not visible. It still takes up space but cannot be clicked or focused.

.element {
  visibility: hidden;
}

.element {
  visibility: visible;
}

Z-Index

Z-Index moves elements behind or in front of other elements, and only works if elements are positioned.

.element {
  z-index: -10;
}

.element {
  z-index: 10;
}

Display

Display determines if the element is visible or not and removes the element from the layout. It is considered a "hard" hide and does not work with transitions.

.element {
  display: none;
}

.element {
  display: block;
}

Pointer Events

Pointer events are for interaction-only "hiding." The element is visible, but it cannot be clicked or interacted with.

.element {
  pointer-events: none;
}

.element {
  pointer-events: auto;
}

Mobile Responsiveness & Break Points

Break Points

Mobile responsiveness for web pages is achieved through media queries.

@media (width > 800px) and (width <= 1000px){
  body {
    background-color: rgb(69, 175, 207);
  }
}

@media (width <= 800px) {
  body {
    background-color: rgb(207, 69, 69);
  }
}

@media screen and (width <= 480px) {
  body {
    background-color: rgb(143, 241, 240);
  }
}