Peter*s Blog

A blog covering my exploration of Ruby, HTML/CSS, JavaScript, and web development in general. About Me.

HTML and CSS Cheat Sheet

I created these notes (which cover HTML and CSS) for myself in preparation for Launch School's front-end exam, and share them here in the hopes that they may prove useful to my fellow students. I based these notes off of Launch School's course materials, and Shaye Howe's wonderful Learn to Code HTML & CSS.

Semantics in HTML

HTML is a semantic language insofar as elements are used to describe the value of content on a page, regardless of that content's ultimate styling or appearance. This is captured in the meaning of the HTML acronym: Hyper-Text Markup Language. A descriptive markup language, of which HTML is one, is concerned with labeling content, rather than styling or otherwise processing it; the task of applying visual styles falls to CSS.

The Box Model

The box model refers to the system in which every element on a web page can be conceived of as a rectangular box with a width, height, padding, borders and margins.

box moxel

By default, the box model is additive. This means that the width and height properties do not describe the total width of the element (i.e., outer edge of margin to opposite outer edge of margin) but rather the dimensions of the content, the innermost component of the box model (the central, 400 x 100 box in the figure above). In order to determine the total width or total height of an element (with total here meaning actual visible/rendered), the appropriate dimension of each component of the box model must be added together from left to right or top to bottom.

Thus, in the example above, width is 400, but total width is:

20 + 6 + 20 + 400 + 20 + 6 + 20 = 492

while height is 100, but total height is:

20 + 6 + 20 + 100 + 20 + 6 + 20 = 192.

These calculations -- and the components of the box model controlled by width and height -- can be changed using the box-sizing property, which is discussed below.

Width and Height

Depending on the value of the box-sizing property, width and height can refer to the dimensions of the content, the padding and content combined, or the padding, content and border combined. Whether width and height can be fixed is determined by the display value.

NB: in this document fixed means given a particular value. For the type of unit, absolute and relative are used.

Padding

The padding property detemines the space inside rather than outside of the border. Vertical padding can be set inside of inline elements. However, this padding will not affect the vertical spacing of elements, and as a result there is a possibility it may bleed upwards or downwards into another element. Padding is transparent, and shows the background color or image for its element.

The longhand form for padding has the following syntax:

padding-left: 10px;

While several shorthands exist:

padding: $vertical_val $horizontal_val;
padding: $top_val $right_val $bottom_val $left_val;

Margin

The margin property is used to determine the amount of space around an element. It can be used to position elements or more generally to give them enough space to be read legibly or viewed clearly by the user. All display values take horizontal margins, but the vertical margins of inline elements cannot be be set, and are always 0. Margin is transparent, but since it falls outside of the border of its element, it shows the background color or image of the parent element.

The longhand and shorthand conventions for margin are the same as for padding.

Borders

Borders are positioned between the padding and the margin, and take three values: width, style and color. The longhand definitions of these values are as follows:

div {
  border-width: 3px;
  border-style: dashed;
  border-color: #ccc;
}

The shorthand takes the values in the same order, but on a single line:

div {
  border: 3px dashed #ccc;
  }

Individual border lines (top, left, bottom, right) can also be targeted according to the following syntax:

div {
  border-bottom: 3px dashed #ccc;
}

Individual values for particular sides can also be targeted specifically:

div {
  border-bottom-color: #ccc;
}

Border Radius

The border-radius property is used to round the corners of an element or the element's border. This property takes both absolute and relative length values. A relative (for example, percent) value will define the radius of each axis of the curve based on the width and height of the content, while an absolute value uses the same value for both axes.

div {
  border-radius: 10px;
  <!--or-->
  border-radius: 10%;
}

In other words, a relative length value of 10% would make the x-axis of the curve 10 percent of the width of the element, and the y-axis of the curve 10 percent of the height. In irregularly proportioned elements, this creates curves at the corners that appear to stretch with the overall shape of the boxes.

Individual box corners can be targeted, as can particular pairs of corners; for a full rundown of border-radius selector targeting syntax, see here.

Box Sizing

The box-sizing property allows us to change the calculations used to determine the total width total height of an element according to the box model. It does so by letting us choose which components of the box model are inside of width and height: content, padding, or border:

div {
  box-sizing: content-box;
  <!--or-->
  box-sizing: padding-box;
  <!--or-->
  box-sizing: border-box;
}

Content Box

The content-box value -- the default for most elements -- follows exactly the schema layed out above under the Box Model heading; width and height determine the dimensions of the innermost component of the box model, the content, while padding and border are added to these base dimensions to determine the total or visual dimensions.

Padding Box

The padding-box value includes any padding in the element's width and height values. The dimensions of the content will shrink to accommodate the padding; thus, if we have a width of 300 pixels and a height of 100 pixels along with a padding value of 20 pixels, the content will have dimensions of 260 pixels x 60 pixels while the visible dimensions remain 300 x 100.

Border Box

The border-box value includes any border width values and padding values in the calculation of the element's width and height. As with padding-box, the content will shrink to accommodate the additional values. So, if we have an element with a border-width of 10 pixels, padding of 20 pixels, and height of 100 pixels and width of 300 pixels, the content's dimensions will be 240 pixels x 40 pixels.

Style Resets

A CSS Style Reset normalizes or resets the styles for all of the available HTML elements to make sure that all elements have the same base styles across all browsers. In practical terms, a reset is a standalone CSS file imported into the main stylesheet, or CSS code copied and pasted to the head of the main stylesheet.

A good collection of resets can be found here.

Floats

The float property is a means of positioning elements on the page, and takes three values, left, right, or none.

img {
  float: left;
}

A floated element (which is pushed to the left or right edge of the parent element depending on the value it is given) is removed from the normal flow of the document. Critically, however, the outer edge of the floated element continues to affect the content of other elements. Thus, non-floated elements render as though the floated element weren't present, with the exception of their content, which seems to 'flow' around the floated element on the page.

This displaced content can, in turn, affect the width and height of its element. In this way, a floated element can directly affect the positioning of the content of other elements, and may indirectly affect the width and height of those other elements depending on the changes in content positioning.

Regardless of any explicit value for a floated element's display property, it will behave like a block element insofar as it can be assigned height, width, and all margin and padding dimensions. However, the default width value will be defined by content.

NB: Normal Document Flow is how a page is rendered in the absence of structural CSS.

CSS Positioning

The position property is used to fine tune the position of elements. It takes three values:

h1 {
  position: static;
  <!--or-->
  position: relative;
  <!--or-->
  position: absolute;
  <!--or-->
  position: fixed;
}

Static

The static value is the default for all elements. Changes resulting from float values notwithstanding, a static positioned element will appear on the page in the order it appears in the markup.

static elements are not considered positioned, and do not create a coordinate system. As a result, a static element cannot serve as a reference point for the offset values of child elements.

Relative

Relative-positioned elements are rendered initially in the normal flow, but can be offset using four property/value pairs: top, right, bottom, left with a length value.

relative positioning creates a coordinate system, allowing child elements to use it for offset positioning.

NB: Even when a relative-positioned element is offset, other elements around it are still rendered as if it were in the normal flow; unlike floated elements, relative-positioned elements do not push content around.

Absolute

Elements with the absolute value for the position property are effectively removed from the document layout, and positioned inside of the nearest containing element that creates a coordinate system for children. If no such elements are present, then the absolute-positioned element uses the <body> element to orient itself.

The default position (i.e., the position when all offset values are zero) for an absolute element is the top-left of the container.

Fixed

Elements with the fixed value for the position property behavior exactly like absolute positioned elements, but use the viewport, rather than any element on the page, as the basis for their positioning. As a result, fixed elements don't move, even when the page scrolls.

The default position for a fixed element is the top left of the viewport.

Offset Properties: Top, Right, Bottom, Left

Offset properties are used to tell a positioned element in what direction and how far to move:

.item {
  position: relative;
  top: 10px;
  left: 10px;
}

Spritesheets

Spritesheets address a potential problem that arises as the number of images on a given page increases, or if multiple, very similar images are displayed on a page and vary depending on some criterion, for example a battery image that varies depending on charge.

Instead of loading a new image each time a change occurs -- which can lead to potentially disruptive page reloads and increased burden on the network -- a sprite sheet can be used. A sprite sheet is a single image that holds multiple versions of the same image. In a CSS selector, a set width and height are defined, and then the background-position property is used to shift the image such that the desired version is displayed:

HTML

<h1>Battery Life Indicator</h1>

<h2>Full</h2>
<div class="battery full"></div>

<h2>Moderate</h2>
<div class="battery moderate"></div>

<h2>Low</h2>
<div class="battery low"></div>

<h2>Empty</h2>
<div class="battery empty"></div>

CSS

@import url("reset.css");
.battery {
  width: 64px;
  height: 124px;
  background: transparent url("path/to/desired/file.png") 0 0 no-repeat;
}
.moderate {
  background-position: 0 -124px;
}
.low {
  background-position: 0 -248px;
}
.empty {
  background-position: 0 -372px;
}

Display Properties

The CSS display property determines how HTML elements are displayed by specifying the type of rendering box the element will use. Although there is a wide variety of values for the display property, the most common are block, inline, inline-block and none.

The visual effect of different display values on elements can be understood in concrete terms using the box model. By understanding how width, height, padding and margin values are affected by each display value, we can accurately predict how an element will be displayed on the page.

Block

Block-level elements are very common, and are typically used to represent larger chunks of content. Block-level elements can nest inline, block and inline-block elements within themselves, occupy the full width of the available space, and by default begin and end with a line break.

Width and Height

Padding

Margin

Inline

Inline-level elements are less common, and are typically used to add more detailed meaning to a portion of a larger set of content. The name recognizes the fact that inline elements are meant to fit easily into a line of text.

Width and Height

Padding

Margin

Inline-Block

inline-block elements combine components of both inline and block displays.

Width and Height

Padding

Margin

None

This display value completely hides the targeted element and all of its children. The page will be rendered as if the element and its children do not exist in the markup.

CSS selectors

CSS selectors are used to target specific elements in a markup for styling. The general model is:

css_selector {
  <!--styling-->
}

There are three basic CSS selectors:

Example Classification Explanation
h1 Type Selector Selects an element by its type
.class_name Class Selector Selects an element by the class attribute value, which may be reused multiple times per page
#id ID Selector Selects an element by the ID attribute value, which is unique and to only be used once per page

Within CSS, all styles cascade from the top of a style sheet to the bottom, allowing different styles to be added or overwritten as the style sheet progresses. In other words, selector definitions lower in the document will overwrite the same definitions located higher in the document.

Every element in CSS also has a specificity weight, which, along with its placement in the cascade, determines how its styles will be rendered. Each selector type (type, class, and ID) has a particular weight. An ID has a higher weight than a class, which has a higher weight than a type selector.

The higher the specificity weight of a given selector, the more superiority that selector is given when a styling conflict occurs. In addition to these basic selector types, there are also many types of complex selectors, which can be grouped as follows:

Child selectors

A child element falls within another element, which becomes that element's parent. Child selectors can target either direct children or any descendent:

Example Classification Explanation
article h2 Descendant Selector Selects an element that resides anywhere within an identified ancestor element
article > p Direct Child Selector Selectss an element that resides immediately inside an identified parent element

Sibling Selectors

Sibling elements share a common parent and are selected on this basis:

Example Classification Explanation
h2 ~ p General Sibling Selector Selects a sibling that follows anywhere after the prior element
h2 + p Adjacent Sibling Selector Selects a sibling that follows directly after the prior sibling

Attribute Selectors

Attribute selectors (including class and id selectors) identify elements based on whether they posses particular attributes or values.

Example Classification Explanation
a[attribute] Attribute Present Selector Selects an element if the given attribute is present
a[attribute=value] Attribute Equals Selector Selects an element if the given attribute value exactly matches the value stated
a[attribute*=value] Attribute Contains Selector Selects an element if the given attribute value contains at least on instance of the value state
a[attribute^=value] Attribute Begins With Selector Selects an element if the given attribute value begins with the value stated
a[attribute$=value] Attribute Ends With Selector Selects an element if the given attribute value ends with the value stated

Pseudo-classes

Pseudo-classes are similar to regular classes except that they are not explicitly stated in the markup; rather, they are dynamically populated as a result of user actions or the document structure, and defined in CSS. Psuedo classes begin with :, and can be classified as follows:

Link Pseudo-class

These pseudo-classes are concerned specifically with links, and dynamically apply styles based on whether a link has been visited or not:

Example Explanation
a:link Selects a link that has not been visited by a user
a:visited Selects a link that has been visited by a user

Action Pseudo-class

These pseudo-classes dynamically style an element depending on the users' actions, expressed through the cursor or focusing on an input.

Example Explanation
a:hover Selects an element when a user has hovered his or her cursor over it
a:active Selects an element when a user has engaged it
a:focus Selects an element when a user has made it their focus point

User Interface State Pseudo-classes

These pseudo-classes are concerned with aspects of the user-interface, in particular with form elements:

Example Explanation
input:enabled Selects an element in the default enabled state
input:disabled Selects an element in the disabled state by way of disabled attribute
input:checked Selects a checkbox or radio-button that has been checked
input:indeterminate Selects a checkbox or radio-button that has an indeterminate state

Structural & Positional Pseudo-classes

These pseudo-classes target elements based on the structure of the markup or the given element's position within it.

Pseudo-classes that mention child (e.g., first-child) consider all sibling elements (peer elements within a single parent element), while those that mention type (e.g., first-of-type) consider only those sibling elements of a certain type.

Pseudo-classes that use the nth notation take an argument (a single number or an algebraic pattern) that targets a group of elements. li:nth-child(4), for example, will select the fourth sibling li element from the beginning of the list, while li:nth-child(4n+7) is interpreted as: 4 * n + 7, resulting in the 7th, 11th, 15th... sibling li element being selected.

In the algebraic pattern (an + b), b can be negative, starting the scan from before index 0. (n) by itself selects all elements, while -n selects all items with index prior to the start of the scan. For example, (-n + 3) will select the first three elements in the list. In short, - value for a can be thought of as commanding the scan to work backwards (up the siblings list), while a positive value can be thought of as commanding the scan to work forwards (down the siblings list).

Example Explanation
:first-child Selects the first sibling element
:last-child Selects the last sibling element
:only-child Selects an element that is the only child of a parent
:first-of-type Selects an element that is first of its type within a parent
:last-of-type Selects an element that is last of its type within a parent
:only-of-type Selects an element that is the only one of its type within a parent
:nth-child(pattern) Select all sibling elements that match the pattern
:nth-of-type(pattern) Select all sibling elements of the specified type that match the pattern

Pseudo-Elements

Pseudo-elements are virtual elements that can be treated as regular HTML elements, but don't actually exist in the document tree; rather, they are created with CSS. Pseudo-elements are preceded by : and require a content attribute/value pair in order to render, even if the value is "".

Before

The :before pseudo element adds content immediately before the element on which it is called. :before is often used to prepend quotation marks, bullet points, or other styling in a consistent way.

After

The :after pseudo element functions like :before, but positions its content immediately after the element on which it is called.

The CSS below demonstrates how :before and :after pseudo-classes can be used to add single quotes around HTML elements of class quote:

.quote:before {
  content: "'";
}
.quote:after {
  content: "'";
}

Media Queries

CSS media queries use what are called breakpoints to trigger the application of a new set of CSS properties. They also allow us to to specify which media types we want to target using one or more media types and combining them with logical operators.

NB: Selectors inside of media queries must have a specificity value that is greater than or equal to any selectors outside of theq uery targeting the same elements; otherwise, the media query will not override the outside styling.

The following media query tells our webpage to set the width of the main element to 100% if the width of the screen is below 480 pixels:

@media (max-width: 480px) {
  main {
    width: 100%;
  }
}