The DOM is a W3C standard that defines:


HTML is an easy-to-read hypertext markup language based in SGML. XHTML is extensible, stricter and designed for XML uses. XML needs to be properly marked with only one root element (HTML), minimum requiring doctype, html, head, body, and title. Attributes must be:

Head: Page Setup

Adding clear, relevant, and concise meta descriptions will boost your search page ranking and SEO. Making your page machine readable will allow search engine spiders to crawl through your content and index your pages. The following tags are suggested:

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="description" content="160 char description with keywords for search engines">
    <meta property="og:title" content="social media share page title">
    <meta property="og:description" content="social media share short description">
    <meta property="og:image" content="https://current-page-main-image.jpg">
    <!--min 1200×630 px, aspect ratio 1.91:1 <1MB-->
    <meta property="og:url" content="https://current-page-link.html">
    <meta name="twitter:card" content="summary_large_image">
    <title>Less than 60 char page summary</title>
    <meta name="robots" content="noindex,nofollow"
    ><!--Pages and links you don't want followed/indexed for search results, default index & follow)-->
    <link rel="apple-touch-icon" sizes="180x180" href="img/icons/touch-icon.png"> <!--Apple touch icon-->
    <link rel="icon" type="image/png" sizes="32x32" href="img/icons/fav-icon.png"><!--Standard favicon-->


Page Tags

<html>Root level element of document <head>Metadata (title, scripts, style sheets) <base>Base URL to use for all relative URLs (add to head) <link>Relationship of current document to external resource <meta>Additional metadata <style>Style information <title>Document title (browser's title bar, page tab)

Semantic Tags

<body>Content of HTML document <main>Dominant content of <body> directly related to central topic <header>Introductory content (nav/intro aids, logo, search, author, etc.) <nav>Section whose purpose is to provide navigation links <article>Self-contained, independently distributable (in syndication) <section>Standalone section catch-all <aside>Content indirectly related to the document's main content <footer>Footer for its nearest sectioning content or sectioning root element <figure>Represents self-contained content <figcaption>Optional caption/legend describing contents of parent <figure> <address>Contact information for person/group <time>Specific period in time <mark>Text marked/highlighted for reference or notation purposes <summary>Specifies a summary/caption/legend for a <details> disclosure box <details>Creates disclosure widget visible when widget toggled "open" <data>Machine-readable translation (if time/date related, <time> must be used <cite>Reference to a cited creative work, including title

Text Tags

<h1> - <h6>Section headings (don’t repeat H1 on a page) <ul>Unordered list (typically bulleted) <ol>Ordered list of items — typically rendered as a numbered list <li>Item in a <ol> or <ul> list <a>Anchor element creates URL to web location <p>Paragraph text <small>Side-comments/small print, like copyright & legal text <q>Short inline quotation (usually added quotations) <blockquote>Text is extended quotation <pre>Preformatted text—exactly as written in HTML <em>Stress emphasis (can be nested to indicate greater degree) <strong>Strong importance, seriousness, or urgency (typically bold) <sub>Subscript element <sup>Superscript element <code>Displays content styled like computer code <samp>Inline text representing sample/quoted output from a computer program <kbd>Span of inline text denoting textual user input from a keyboard/etc. <var>Variable name (math/programming) <i>Differ from normal text (display only, use <em> otherwise) <b>Bring Attention (style only, use <strong> for context) <s>Text strikethrough, no longer relevant/accurate text <u>Shows text is rendered with non-textual annotation

Content Tags

<div>Generic container requiring style <span>Generic inline container, group elements for styling purposes <abbr>Abbreviation/acronym, optional title attribute description <dfn>Indicate term being defined within the context of sentence <dl>Description list (group of dt terms, ex. Glossary or list of key-value pairs <dt>Specifies term in description/definition list, must be used inside <dl> <dd>Provides description/definition/value for preceding term in description list <hr>Thematic break between paragraph-level elements (ex. Topic shift) <br>Line break (carriage return) useful for poems/addresses <del>Editing mark = deleting text <ins>Editing mark = adding text <wbr>Word break opportunity for lengthy text

Media Tags

<img>Embeds an image <embed>Embeds external content at the specified point in the document <audio>Embed sound content, src attribute/element <video>Embeds a media player which supports video playback <track>Used as a child <audio> & <video>, timed text tracks (subtitles) <iframe>Inline Frame, nested browsing/embedding another HTML page <object>External resource (image, a nested browsing context, or for a plugin) <param>Defines parameters for an <object> element <picture>Contains <source> elements & <img> for alternative image versions <canvas>Use with canvas scripting API/WebGL API to draw graphics and animations <source>Specifies multiple media resources for <picture>, <audio>, or <video> <noscript>Adds HTML if a script type is unsupported/scripting is turned off <script> Embed or reference executable code; typically JS

Consider making images responsive. Add max-width of 100% to make sure the image is never wider than the container it is in, and add auto height to make the image keep its original aspect ratio.

An easy want to make sure your image looks good on high pixel density displays is to resize it to be half the original size (length x width).

Table Tags

<table>Tabular data, rows and columns of cells containing data <caption>Caption/title of table, always appears as the first child of <table> <thead>Defines a set of rows (head of the table columns) <th>Defines cell as header of a group of table cells <tbody>Encapsulates a set of table rows (<tr> elements, body of table) <tr>Defines a row of cells in a table <td>A cell of the table containing data <tfoot>Set of rows summarizing the columns of the table <colgroup>Defines a group of columns within a table <col>Column within a table, generally found within <colgroup>

Data Tags

<button>Clickable button <datalist>Contains a set of <option> to choose from within other controls <fieldset>Used to group several controls as well as labels (<label>) within a form <form>Document section with interactive controls to submit info to web server <input>Interactive controls for web-based forms in order to accept data from the user <label>Caption for an item in a user interface <legend>Caption for the content of its parent <fieldset> <meter>Represents either a scalar value within a known range or a fractional value <optgroup>Creates a grouping of options within a <select> element <option>Define an item contained in <select>, <optgroup>, or <datalist> <output>Container element, site/app can inject results of calculation/user outcome <progress>Displays indicator showing the completion progress of a task (typically bar) <select>Control that provides a menu of options <textarea>Multi-line plain-text editing control, users can enter sizable free-form text <dialog>Dialog box/interactive component, such as an inspector/window <slot>Placeholder inside a web component that you can fill with your own markup <template>Holds HTML to be rendered later using JS

Special Use Tags

<bdi>Tells browser's bidirectional algorithm to treat text in isolation <bdo>Override current directionality of text <rb>Ruby Base delimits the base text component of a <ruby> annotation <rp>Fall-back parentheses for browsers that don’t support ruby annotation <rt>Specifies ruby text component inside <ruby> element <rtc>Ruby Text Container = semantic annotations of characters presented <ruby>Ruby annotation to show pronunciation of East Asian characters <menu>Group of commands that a user can perform or activate

HTML Attributes

Global Attributes

classSpecifies one or more classnames for an element idSpecifies a unique id for an element titleSpecifies extra information about an element tabindexSpecifies the tabbing order of an element hiddenSpecifies that an element is not yet, or is no longer, relevant accesskeySpecifies a shortcut key to activate/focus an element data-*Used to store custom data private to the page or application draggableSpecifies whether an element is draggable or not dropzoneSpecifies whether the dragged data is copied, moved, or linked, when dropped contentSpecifies whether the content is editable or not (contenteditable) itemidThe unique, global identifier of an item itempropUsed to add properties to an item, name and value pair itemrefProvides a list of element ids (not itemids), additional properties elsewhere itemscopeCreates the Item and defines the scope of the itemtype associated with it itemtypeSpecifies URL of vocabulary used to define itemprops in the data structure dirSpecifies the text direction for the content in an element spellcheckSpecifies whether spelling and grammar should be checked or not translateSpecifies whether the content of an element should be translated or not langSpecifies the language of the element's content styleSpecifies an inline CSS style for an element slotAssigns a slot in a shadow DOM shadow tree to an element partAllows CSS to select and style specific elements in a shadow tree via ::part

Form Attributes

formactionbutton, input: indicates the action, overriding action defined in form formenctypebutton, input: If (type="submit"), sets encoding type formmethodbutton, input: If (type="submit"), sets method (GET, POST, etc.) novalidate button, input: If (type="submit"), not to be validated (formnovalidate) formtargetbutton, input; If (type="submit"), display response browser target acceptform, input: list of types the server accepts, typically a file type -charsetform list of supported charsets (accept-charset) actionform processing the information submitted via the form enctypeform: defines the content type of the form date when the method is POST method*form: defines HTTP method to submit the form (GET default or POST) novalidateform: shouldn't be validated when submitted autocompleteform, input, select, textarea: automatically completed by the browser autofocusbutton, input, select, textarea focused after page load disabledbutton, fieldset, input, optgroup, option, select, textarea forlabel, output: describes elements which belongs to this one formbutton, fieldset, input, label, object, output, progress, select, textarea namebutton, form, fieldset, iframe, input, object, output, select, textarea captureinput: from the HTML Media Capture checkedinput: indicates whether element should be checked on load dirnameinput, textarea: specifies text direction of the input field will be submitted listinput: identifies a list of pre-defined options to suggest to the user maxinput, progress: indicates the maximum value allowed maxlengthinput, textarea: maximum number of characters allowed in the element minlengthinput, textarea: minimum number of characters allowed in the element. mininput: indicates the minimum value allowed multipleinput, select: indicates whether multiple values can be entered in an input patterninput: defines regular expression which value will be validated against placeholderinput, textarea: hints to user what can be entered in the field readonlyinput, textarea: Indicates whether the element can be edited requiredinput, select, textarea Indicates whether this element is required to fill sizeinput, select: Width of element (px or # characters for text/password) stepinput: numeric input types, steps allowed when entering numbers colstextarea: defines the number of columns in a textarea enterkeyhinttextarea, contenteditable: action label/icon for enter key on virtual keyboards inputmodetextarea, contenteditable: hints type of data that can be entered rowstextarea: Defines the number of rows in a text area wraptextarea: Indicates whether the text should be wrapped labeloptgroup, option: specifies a user-readable title of the element selectedoption: Defines a value which will be selected on page load

*Get vs. Post Method: The action part of where the form information should be going. Form method GET = information from input fields will show up in URL bar. This is sometimes useful for trying to get information out of the URL bar. DO NOT USE THIS METHOD FOR SENSITIVE INFORMATION GOING INTO BROWSER. Instead use the POST method. Post method will send the same information to the server without showing information in the URL bar. GET/POST and server-side actions.

When creating forms, best practice for assistive technology: associate the input by wrapping it around with a label element. All related radio button inputs should have the same name attribute to create a button group. Give radio and checkbox inputs the value attribute so data sent will make sense (use input text label in lower case). The value of the for attribute must be the same as the value of the id attribute of the form control.

<label for="good">
  <input id="good" value="good" type="radio" name="feeling">
<label for="not-so-good">
  <input id="not-so-good" value="not-so-good" type="radio" name="feeling">Not So Good

Link Attributes

asyncscript: executes the script asynchronously charsetmeta, script: declares the character encoding of the page or script contentmeta: value associated with http-equiv or name depending on context http-equivmeta: defines a pragma directive deferscript: script should be executed after the page has been parsed integritylink, script: subresource integrity value allows browsers to verify fetched languagescript: defines the script language used in the element downloada: Indicates hyperlink is to be used for downloading a resource hrefa, base, link: URL of a linked resource hreflanga, link: specifies the language of the linked resource mediaa, link, source: hints media for which the linked resource was designed pinga: specifies space-separated list of URLs to be notified if a user follows link referrerpolicya, area, iframe, img, link, script: Specifies referrer sent rela, area, link: target relationship to link (rel="manifest" for cache manifest) targeta, base, form: specifies where to display the linked resource

Media Attributes*

alignhr, iframe, img, table tags = horizontal alignment altimg, area, input alternative text in case an image can’t display dataobject: specifies the URL of the resource heightcanvas, embed, iframe, img, input, object, video only widthcanvas, embed, iframe, img, input, object, video only importance iframe, img, link, script: indicates relative fetch priority for resource crossoriginaudio, img, link, script, video: handling cross-origin requests sizeslink, img, source: 1+ strings separated commas, set of source sizes srcaudio, embed, iframe, img, input, script, source, video – URL of embedded srcsetimg, source: One or more responsive image candidates decodingimg: indicates the preferred method to decode the image intrinsicsizeimg: ignore intrinsic size of image, pretend size specified in the attribute loadingimg, iframe: indicates if element (loading="lazy") or (loading="eager") autoplayaudio, video play media ASAP (video allowed with no sound) bufferedaudio, video contains the time range of already buffered media controlsaudio, video: browser showing playback controls to the user loopaudio, video: whether media should loop after finished mutedaudio, video: Indicates whether audio will be silent on page load preloadaudio, video: Whether whole resource, parts of it, or nothing preloaded postervideo: URL indicating poster frame to show until the user plays or seeks cspiframe: specifies Content Security Policy doc agree to enforce upon itself allowiframe specifies a feature-policy for the iframe sandboxiframe: stops a document loaded in an iframe from using certain features srcdociframe: Inline HTML to embed, overriding the src attribute

*HTML5 makes it easy to add video and music onto your website. You can add multiple file sources for the browser to go through and find it. .mp3 files are highly recommended for audio, and .mp4 files are highly recommended for video (fast loading, small file, universally adopted). For video play, please note that browsers will only allow autoplay if any sound is muted.

HTML Input Types

buttonA push button with no default behavior displaying attribute value, default empty checkboxA check box allowing single values to be selected/deselected colorA control for specifying a color; opening a color picker when active dateA control for entering a date (yy/mm/dd) date picker/numeric wheels datetimeEnter date/time with no time zone (datetime-local) monthA control for entering a month and year, with no time zone timeTime value with no time zone weekEnter date consisting of a week-year number + week number with no time zone emailA field for editing an e-mail address (validation) fileA control that lets the user select a file hiddenA control not displayed but whose value is submitted to the server imageA graphical submit button -- displaying an image defined with the src attribute number A control for entering a number; displays a spinner and adds default validation passwordA single-line text field whose value is obscured. Will alert user if site is not secure radioAllows single value to be selected out of multiple choices with same name value rangeRange widget defaulting to the middle value (use with min/max to define range) resetResets the contents of the form to default values (not recommended) searchSingle-line text field for entering search strings, line breaks removed from input submitA button that submits the form telEnter telephone number, sometimes looks like telephone keypad textDefault value (single-line text field), line-breaks removed from input urlEnter URL (text with validation parameters)

HTML Entities

Reserved characters in HTML must be replaced with character entities. Below is a summary of some useful entity names (remove space between).

 non-breaking space: & nbsp <less than: & lt; >greater than: & gt; &ampersand: & amp; "double quotation mark: & quot; 'single q mark (apostrophe): & apos; ¢cent: & cent; £pound: & pound; ¥yen: & yen; euro: & euro; ©copyright: & copy; ®registered trademark: &r eg;

HTML Table Style

ColorChange colors in th,& td BordersAdd borders to table, th & td (top, right, bottom, left) CollapseCollapse into single border Width/HeightAdd dimensions to table, th & td Horizontal AlignAlign text to left, right and center of cells Vertical AlignAlign text to top, middle, or bottom of cells PaddingAdd padding to th & td LayoutDefine how table is laid out (fixed vs auto) Change on HoverUse pseudo-class :hover to change color/styling, etc. Every Other RowUse pseudo-class :nth-child(even or odd) to change style Empty CellsDisplay no borders - empty-cells: hide; CaptionAdd table caption and place on top or bottom Colspan & RowspanMerging rows/columns across the table

CSS Colors

Named colors are simply words such as black, darkblue, & violet. These pre-defined colors are great for testing boundary boxes. RGB colors are made from 3 light colors: red, green, and blue, referenced in order. Every color on your display is created by mixing these three colors together in different ratios. Each color is set to a value between 0 and 255 (0 = absence of light, 255 = maximum brightness). HSL is another way of expressing the same colors (all colors in web development are in the RGB color space) but is instead composed of hue (0-360), saturation (0-100%), and lightness (0-100%). HSL is great for easily creating different shades of a base color for simultaneous contrast.

Both RGB and HSL also take in an alpha value which indicates transparency. This is a decimal value between 0 (fully transparent) to 1 (fully opaque). With transparency enabled, rgb becomes rgba(#,#,#,.#) and hsl becomes hsla(#,%,%,.#). Finally, HEX codes are shorthand versions of all the colors represented in 6 digits. HEX codes can also be sortened to 3 digits if the first 3 repeat, and is the most popular option in web design. Remember to test your color usage for contrast. Color alone should not convey important information. Foreground and background colors need sufficient contrast so colorblind users can distinguish them. For example, in the box below the background has been set to a dark navy and the text color has been set to white. The equivalents of these colors are coded below:

#css-color {background-color: navy; color: white;}
#css-color {background-color: #000080; color: #fff;}
#css-color {background-color: rgb(0, 0, 128); color: rgb(255, 255, 255);}
#css-color {background-color: hsl(240, 100%, 25%); color: hsl(0, 0%, 100%);}

CSS Box Model

The box model is the foundation to styling content with CSS. Margin create space around elements outside of borders. If set to a negative margin, the element will grow. It can be specified as margin-top/right/bottom/left with a measurement unit. Auto is a helpful value the browser automatically calculates and can help center an object when both margin-left and -right are set. The outline is a line drawn around elements outside borders to emphasize. It includes the properties outline-style, outline-color, outline-width, and outline-offset. The border frames the block element. Adding a border radius will produce rounded corners (and even make a square element circle). Padding creates space around elements within the borders. You can use box-sizing: border-box; to contain space inside box so it doesn't interfer with the rest of the layout.

Box sizing set to border-box: 400x200px box with padding of 30px, border of 20px, outline of 10px, and margin of 40px.


CSS Display & Position


By default, certain HTML elements like p, h1-h5, and div have a block display value, which means they take up the space of the full width of the line they're on, even if their specified width isn't that long. This means that the rest of the elements element on the page have to start on the next line. Other elements like b and span are inline, meaning they can sit right next to each other on the page. We can change these default properties using the display value. The display value specifies how an element should look/behave, and is comprised of 4 main states.

display: none;hidden (can be toggled with javascript or pseudo classes) display: inline;elements sit next to each other on the same line display: block;*elements stand out and have their own line display: inline-block;elements have specified width and sit next to each other

If block elements don't have any content, or if an element is natively inline, the element must have a specified width for block display.


Elements can be positioned in a variety of ways using the position: property

position: static;Default order - document flow position: relative;Positioned relative to its normal position in the flow position: absolute;Positioned relative to its first positioned (not static) parent position: fixed;Positioned relative to the browser window position: sticky;Based on user's scroll position

Once we specify the position, we can then reposition the element using the following (please note these properties don't work unless an element has a declared position, ie not the default position: static;):

top: measurement unit;Distance from top right: measurement unit;Distance from right bottom: measurement unit;Distance from bottom left: measurement unit;Distance from left z-index: #;3D position/z-axis

position: relative; simply gives an element a new position relative to its normal one. So if a box normally sits at the top left, you can use position: relative; + left: 20px; to push it 20 pixels to the right (left = distance from the left, so effectively moving right). position: relative; doesn't affect the positions of the other elements in the same parent.

position: absolute; gives an element a position relative to its parent (I know, the descriptions can get a bit confusing!). So it relies on its parent container to be told where to go. Elements with the position: absolute; value are removed from the normal document flow and automatically positioned at the top left corner of its parent. From there, you can use the top/right/bottom/left properties to get it where you want it to go. Also note that other elements are affected by this positioning and will act as if this element isn't there, or has been removed completely from a page.

position: fixed; elements are also removed from the normal document flow but are only relative to the html document and are not affected by scrolling. ELements are not relevent to its parent container anymore. (Think of a header that doesn't move, no matter how far down you scroll the page - it always has a place in your browser/window.)

position: sticky; behaves like a relatively positioned element until it reaches a declared point, at which point it becomes fixed in the window. This value is supported in all modern browsers, except Safari needs a -webkit- prefix attached.

As previously discussed, we have top/right/bottom/left to work with. Additionally, we also have the z-index. the z-index simply sets the order for which elements appear, forward or backward. The higher the number, the closer it is to you. So an element with z-index: 1; will be behind an element with z-index: 2;, or even z-index: 1000;. The z-index can also have a negative value and behaves the way you expect - anything with a negative value will be behind the default value of 0.


Float mimics print layouts by allowing elements like pictures to float in the document. Float is related to two properties: float and clear. You can float an element with float: left; or float: right;, and float multiple elements at the same time. clear: none; Default, allows floating elements on both sides. clear: left; No elements allowed to float on the left. clear: right; No elements allowed to float on the right. clear: both; None allowed on either side

Common CSS Properties

Alphabetized list of common CSS properties (left) and matching DOM notation for Javascript(right)

background*background background-attachmentbackgroundAttachment background-colorbackgroundColor background-imagebackgroundImage background-positionbackgroundPosition background-repeatbackgroundRepeat border*border border-bottomborderBottom border-bottom-colorborderBottomColor border-bottom-styleborderBottomStyle border-bottom-widthborderBottomWidth border-colorborderColor border-leftborderLeft border-left-colorborderLeftColor border-left-styleborderLeftStyle border-left-widthborderLeftWidth border-rightborderRight border-right-colorborderRightColor border-right-styleborderRightStyle border-right-widthborderRightWidth border-styleborderStyle border-topborderTop border-top-colorborderTopColor border-top-styleborderTopStyle border-top-widthborderTopWidth border-widthborderWidth box-shadowboxShadow clearclear clip-pathclipPath colorcolor cursorcursor displaydisplay filterfilter floatcssFloat font*font font-familyfontFamily font-sizefontSize font-variantfontVariant font-weightfontWeight heightheight leftleft letter-spacingletterSpacing line-heightlineHeight list-stylelistStyle list-style-imagelistStyleImage list-style-positionlistStylePosition list-style-typelistStyleType margin*margin margin-bottommarginBottom margin-left marginLeft margin-rightmarginRight margin-topmarginTop opacityopacity overflowoverflow padding*padding padding-bottompaddingBottom padding-leftpaddingLeft padding-rightpaddingRight padding-toppaddingTop page-break-afterpageBreakAfter page-break-beforepageBreakBefore positionposition resizeresize= stroke-dasharraystrokeDasharray stroke-dashoffsetstrokeDashoffset stroke-widthstrokeWidth text-aligntextAlign text-decorationtextDecoration text-indenttextIndent text-shadowtextShadow text-transformtextTransform toptop vertical-alignverticalAlign visibilityvisibility widthwidth z-indexzIndex

*CSS Shorthand properties referenced above, see section below.

CSS Shorthand

  1. one-value syntax: all edges and corners
  2. two-value syntax: parallel edges (top/bottom first) and corners (top left/bottom right)
  3. three-value syntax: see above + third value bottom edge/bottom right
  4. four-value syntax: starting at top/left, going clockwise

all:resets all of an element's properties but unicode-bidi & direction animation:name, duration, timing, delay, count, direction, fill, state background: color, image, repeat, attachment, position border:width, style, color border-x:x-width, x-style, x-color border-color:top-color, right-color, bottom-color, left-color border-image:source, slice, width, outset, repeat border-radius:top-left, top-right, bottom-right, bottom-left border-style:top-style, right-style, bottom-style, left-style border-width:top-width, right-width, bottom-width, left-width column-rule:rule-width, rule-style, rule-color columns:column-width, column-count flex:flex-grow, flex-shrink, flex-basis flex-flow:flex-direction, flex-wrap font:style, variant, weight, size/line-height, family grid:template-rows, -columns, -areas, auto-rows, auto-columns, auto-flow grid-area:grid-row-start, grid-column-start, grid-row-end, grid-column-end grid-column:grid-column-start, grid-column-end grid-row:grid-row-start, grid-row-end grid-template:grid-template-columns, grid-template-rows, grid-template-areas list-style:list-style-type, list-style-position, list-style-image margin:margin-top, margin-right, margin-bottom, margin-left padding:padding-top, padding-right, padding-bottom, padding-left offset:position, path, distance, anchor: auto, rotate: auto outline:outline-color, outline-style, outline-width overflow:overflow-x, overflow-y place-content:align-content, justify-content place-items:align-items, justify-items place-self:align-self, justify-self text-decoration:line, color, style, thickness transition:property, duration, timing-function, delay

CSS Reset

Browsers may treat certain elements differently, leading to a variation in the visual appearance of your page. Many people prefer using a "reset" codebase on your global CSS so you can start at a baseline and define your styles as you go. Below is a suggested reset template to help get started:

:root {
  /*define global variables here*/
  --baseFont: san-serif;
* {
  margin: 0; 
  padding: 0; 
  border: 0;
  vertical-align: baseline; 
  box-sizing: border-box;
body {
  min-height: 100vh; 
  width: 100%;
  scroll-behavior: smooth; 
  text-rendering: optimizeSpeed;
  font: 1rem/1 var(--baseFont);
  /*add page grid here as needed*/

CSS Selectors

.classSelects all elements that share the class .class1.class2Selects all elements with class1 and class2 set .class1 .class2 Selects all with .class2 that is a descendant of element with .class1 #idSelects the element with id *Selects all elements elementSelects all of the type of element p.introSelects all p elements with class="intro" div, pSelects all div elements and all p elements div pSelects all p elements inside div elements div > pSelects all p elements where the parent is a div element div + pSelects all p elements that are placed immediately after div elements p ~ ulSelects every ul element that are preceded by a p element


[attribute][target]: Selects all elements with a target attribute [attribute=value][target=_blank]: Selects all elements with target="_blank" [attribute~=value][title~=flower]: Selects all with a title attribute containing "flower" [attribute|=value][lang|=en]: Selects all with a lang attribute value starting with "en" [attribute^=value]a[href^="https"]: Selects a whose href attribute begins with "https" [attribute$=value]a[href$=".pdf"]: Selects a whose href attribute value ends with ".pdf" [attribute*=value]a[href*="sub"]: Selects a whose href attribute value contains substring

Pseudo Classes

:first-childp:first-child - Selects every p elements that is the first child of its parent :last-childp:last-child - Selects every p elements that is the last child of its parent :only-childp:only-child - Selects every p element that is the only child of its parent :first-of-typep:first-of-type - Selects every p that is the first p element of its parent :last-of-typep:last-of-type- Selects every p that is the last p element of its parent :nth-child(n)p:nth-child(2) -Selects every p element that is the second child of its parent :nth-last(n)p:nth-last-child(2) - Selects p 2nd child of parent, counting from last child :nth-last-of(n)p:nth-last-of-type(2) - Selects 2nd p of its parent, counting from last child :nth-of-type(n)p:nth-of-type(2) - Selects 2nd p element of its parent :only-of-typep:only-of-type - Selects every p that is the only p element of its parent :rootroot - Selects the document's root element :activea:active - Selects the active link :hovera:hover - Selects links on mouse over :visiteda:visited - Selects all visited links :linka:link Selects all unvisited links :target#news:target - Selects current active #news (clicked on URL anchor name) :emptyp:empty - Selects every p element that has no children :not(selector):not(p) Selects every element that is not a p element :lang(lang)p:lang(it) - Selects every p element with lang attribute value beginning "it" :checkedinput:checked - Selects every checked input element :defaultinput:default – Selects the default input element :enabledinput:enabled - Selects every enabled input element :disabledinput:disabled - Selects every disabled input element :focusinput:focus - Selects the input element that has focus :in-rangeinput:in-range - Selects input elements with a value within a specified range :invalidinput:invalid - Selects all input elements with an invalid value :optionalinput:optional - Selects input elements with no "required" attribute :out-of-rangeinput:out-of-range - Selects input elements with value outside a range :read-onlyinput:read-only - Selects input elements with a "readonly" attribute specified :read-writeinput:read-write - Selects input elements with no "readonly" attribute :requiredinput:required Selects input elements with a "required" attribute specified :validinput:valid - Selects all input elements with a valid value

Pseudo Elements

::afterp::after - Insert content after every p element ::beforep::before - Insert content before every p element ::first-letterp::first-letter - Selects the first letter of every p element ::first-linep::first-line - Selects the first line of every p element ::selectionp::selection - Selects the portion of an element selected by a user

CSS Units

Absolute Units

cmcentimeters mmmillimeters ininches (1in = 96px = 2.54cm) pxpixels (1px = 1/96th of 1in) ptpoints (1pt = 1/72 of 1in) pcpicas (1pc = 12 pt)

Relative Units

em* Relative to font-size of the element (padding/margin) exRelative to the x-height of the current font (rarely used) chRelative to width of the "0" (zero) rem*Relative to font-size of the root element (font size) vw**Relative to 1% of the width of the viewport vh**Relative to 1% of the height of the viewport vmin*Relative to 1% of viewport's* smaller dimension vmax*Relative to 1% of viewport's* larger dimension %Relative to the parent element (good for widths)

*em & rem units are practical in creating responsive layout. **Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm. Consider using viewport units for responsive typography.

CSS Flexbox

Flexbox is ideal for one-dimensional layouts. Simply set your container as display:flex, and start defining your layout. When you set flex container as a row, items are placed side-by-side left-to-right on main axis (X). When you set flex container a s column, items are vertically stacked from top to bottom on main axis (Y).

Flex Container

justify-content distributes flex items along its main axis:

Align-items is similar, but distributes flex items along cross axis:

By default, flex box container will fit all items together. flex-wrap property tells CSS to wrap items.

Flex Items

flex-shrink: allows an item to shrink if the flex container is too small (as it resizes down). The flex-shrink property takes numbers as values. The higher the number, the more it will shrink compared to the other items in the container. For example, if one item has a flex-shrink value of 1 and the other has a flex-shrink value of 2, the one with the value of 2 will shrink twice as much.

flex-grow: controls the size of items when the parent container expands. If one item has a flex-grow value of 1 and the other has a flex-grow value of 2, the latter will grow twice as much as the other.

The flex-basis property specifies the initial size of the item before CSS makes adjustments with flex-shrink or flex-grow. The units used by the flex-basis property are the same as other size properties (px, em, %, etc.). The value auto sizes items based on the content.

Flex shortcut sets the flex-grow, flex-shrink, and flex-basis properties.

The order property is used to tell CSS the order of how flex items appear in the flex container. By default, items will appear in the same order they come in the source HTML. The property takes numbers as values, and negative numbers can be used.

align-self allows you to adjust each item's alignment individually, instead of setting them all at once. This is useful since other common adjustment techniques using the CSS properties float, clear, and vertical-align do not work on flex items. align-self accepts the same values as align-items and will override any value set by the align-items property.

CSS Grid

Grid Container

CSS Grid is helpful in creating two-dimensional layouts. Simply declare display:grid in your container element to get started. You first need to declare a template through grid-template-columns or grid-template-rows. You can use absolute and relative units to define the sizes. You can also use fr (fraction of the available space), auto (adjust to content automatically), and % (adjust based on width of container).

You can then define the gap in the grid (grid-column-gap or grid-row-gap, shortened to grid-gap).

Grid Items

The grid-column property and the grid-row property are used on grid items to declare how much space they will take up on the layout. Lines that create the grid are numbered starting with 1 at the top left corner of the grid and move right for columns and down for rows. To control the amount of columns an item will consume, you can use the grid-column property in conjunction with the line numbers you want the item to start and stop at. For example you can declare an element to have grid-column: 1 / 3; meaning they will take up two columns from the left, or declare grid-column 1 / span 2; for the same effect.

The content of each item is located in a cell. You can align the content's position within its cell horizontally using the justify-self property on a grid item. This CSS Grid property accepts the following values:

You can also align items vertically. Use the align-self property on an item. This property accepts all the same values as justify-self

Sometimes you want all the items in your CSS Grid to share the same alignment. You can align them all at once horizontally by using justify-items on your grid container (accepting the same values as above). Using the align-items property on a grid container will set the vertical alignment as well.

You can group cells of your grid together into a marged area and give it a custom name. The code below merges the top three cells together into an area header, bottom three into a footer, and makes two areas in the middle, a side callout and a main content section. Every word in the code represents a cell and every pair of quotation marks represent a row. In addition to custom labels, you can use a period (.) to designate an empty cell in the grid.

After creating an area's template for your grid container, you can place an item in your custom area by referencing the name you gave it. To do this, you use the grid-area property on an item like below. This lets the grid know that you want the item1 class to go in the area named header. In this case, the item will use the entire top row because that whole row is named as the header area.

div {
  display: grid;
  "header header header"
  "side content content"
  "footer footer footer";
.item1 {
  grid-area: header;

If your grid doesn't have an areas template to reference, you can create an area on the fly for an item to be placed like this: item1 {grid-area: 1/1/2/4;}. The numbers define horizontal line to start at / vertical line to start at / horizontal line to end at / vertical line to end at. So the item in the example will consume the rows between lines 1 and 2, and the columns between lines 1 and 4. You can use repeat(number, width); for many repetitive rows or columns. You can also repeat multiple values with the repeat function and insert the function amongst other values when defining a grid structure. For example, grid-template-columns: repeat(2, 1fr 50px) 20px; means grid-template-columns: 1fr 50px 1fr 50px 20px;

When using grid-template-columns and grid-template-rows, you can also use the function minmax. It's used to limit the size of items when the grid container changes size. To do this you need to specify the acceptable size range for your item. For example, grid-template-columns: 100px minmax(50px, 200px); creates two columns. The first is 100px wide, and the second has the minimum width of 50px and the maximum width of 200px.

Turning an element into a grid only affects the behavior of its direct descendants. So by turning a direct descendant into a grid, you have a grid within a grid. For example, by setting the display and grid-template-columns properties of the element with the item3 class, you create a grid within your grid.

Flexible Layouts with auto-fill/auto-fit

The repeat function comes with an option called auto-fill. This allows you to automatically insert as many rows or columns of your desired size as possible depending on the size of the container. You can create flexible layouts when combining auto-fill with minmax, like this: repeat(auto-fill, minmax(60px, 1fr)); When the container changes size, this setup keeps inserting 60px columns and stretching them until it can insert another one. If your container can't fit all your items on one row, it will move them down to a new one. auto-fit works almost identically to auto-fill. The only difference is that when the container's size exceeds the size of all the items combined, auto-fill keeps inserting empty rows or columns and pushes your items to the side.

CSS Special Values

:inheritSets the property value applied to be the same as parent element :initialApplies default value of a property (set by browser) :unsetResets the property to its natural value (initial unless set inherit) :revertReverts to value it would have had if the current origin has no styles :x !importantIgnore previous rules and override with immediate :transparentUse anywhere color values are accepted :currentcolorUse current color on properties that don’t receive it by default :0 autoValue of property adjusted automatically according to the content/context :hiddenVisibility: hides element from browser, remains in space/document flow :noneDisplay: removes element from document flow

CSS Filter

The filter CSS adds graphical effects to an element (usually images). Check out the predefined filters below, or use filter:(url); to locate a custom SVG filter (XML file).

filter-example100% Greyscale
filter-example20px Blur
filter-example120% Brightness
filter-example200% Contrast
filter-example5px Drop Shadow
filter-exampleHue Rotate -50 Degrees
filter-exampleInvert 100%
filter-example50% Opacity
filter-example150% Saturation
filter-example100% Sepia

CSS Transforms


matrix(n,x6)transformation, use a matrix of six values translate(x,y)translation, move the element along X+Y-axis translateX(n)translation, move the element along the X-axis translateY(n)translation, move the element along the Y-axis scale(x,y)scale transformation, change elements width+height scaleX(n)scale transformation, changeelement's width scaleY(n)scale transformation, change the element's height rotate(angle)rotation, the angle specified in the parameter skew(x,y)skew transformation along the X- and the Y-axis skewX(angle)skew transformation along the X-axis skewY(angle)skew transformation along the Y-axis


matrix3d(n,x16) 3D transformation, 4x4 matrix of 16 values translate3d[translate3d(x,y,z)] 3D translation translateX(x) 3D translation, use only the value for the X-axis translateY(y) 3D translation, use only the value for the Y-axis translateZ(z) 3D translation, use only the value for the Z-axis scale3d(x,y,z) 3D scale transformation scaleX(x) 3D scale transformation by give a value for the X-axis scaleY(y) 3D scale transformation by give a value for the Y-axis scaleZ(z) 3D scale transformation by give a value for the Z-axis rotate3d[rotate3d(x,y,z,angle)] 3D rotation rotateX(ang) 3D rotation along the X-axis rotateY(ang) 3D rotation along the Y-axis rotateZ(ang) 3D rotation along the Z-axis perspective(n) perspective view for a 3D transformed element

CSS Functions

attr()Returns the value of an attribute of the selected element calc()Allows you to perform calculations to determine CSS property values cubic-bezier()Defines a Cubic Bezier curve hsl()Defines colors using the Hue-Saturation-Lightness model (HSL) hsla()Defines colors using the Hue-Saturation-Lightness-Alpha model (HSLA) linear-grad()[linear-gradient()] Sets as bg image, define 2+colors (top to bottom) radial-grad()[radial-gradient()] Sets as by image, define 2+colors (center to edges) repeating-l()[repeating-linear-gradient()] Repeats a linear gradient repeating-r()[repeating-radial-gradient()]Repeats a radial gradient var()Inserts the value of a custom property

CSS @media Features

Types: general device category, optional (all type implied) unless using “not” or “only” logic. Can combine statements to make Boolean logic.


allSuitable for all devices printpaged material and documents viewed in print preview mode screenIntended primarily for screens speechIntended for speech synthesizers


prefers-color:(prefers-color-scheme) Detect user preference of light or dark color scheme prefers-cont:(prefers-contrast) Detects user request of increase/decrease color contrast reduced-mot:(prefers-reduced-motion) The user prefers less motion on the page reduced-tran:(prefers-reduced-transparency) The user prefers reduced transparency


hover:Does primary input mechanism allow the user to hover over elements? any-hover:Does available input mechanism allow the user to hover over elements? any-pointer:Is any available input mechanism a pointing device? pointer:Is the primary input mechanism a pointing device? if so, how accurate? scripting:Detects whether scripting (i.e. JavaScript) is available update: How frequently the device can modify the appearance of content scan: Scanning process of the device


monochrome:Bits per pixel in device's monochrome frame buffer (0 if not monochrome) color:# bits per color component of the device (zero if device isn't color) color-gamut:~range of colors supported by the user agent and device color-index:# entries in device's color lookup table, (zero if device has no table) forced-colors:Detect whether user agent restricts color pallet inverted:(inverted-colors) Is the user agent or underlying OS inverting colors? light-level:Light level of the environment


width:Width of the viewport including width of scrollbar resolution:Pixel density of the device orientation:Orientation of the viewport aspect-ratio:Width-to-height aspect ratio of the viewport display-mode:The display mode of the application grid:Does the device use a grid or bitmap screen? height:Height of the viewport overflow-bl:(overflow-block) How does device handle overflow viewport along block axis? overflow-inl:(overflow-inline) Can content overflow viewport along inline axis be scrolled?


Make your content accessibile with the following guidelines:

A negative tabindex value (typically -1) indicates that an element is focusable, but is not reachable by the keyboard. This method is generally used to bring focus to content programmatically (like when a div used for a pop-up window is activated). Tabindex overrides the default on the page so make sure it doesn’t confuse your user.

Position screen-reader only accessibility styles on the page like:

.screen-reader-only {
    position: absolute;
    left: -10000px;
    width: 1px;
    height: 1px;
    top: auto;
    overflow: hidden;

Aria Tags

ARIA tags (Accessible Rich Internet Applications) are attributes that enhance access for users who are browsing the internet with assistive technology such as screenreaders. An example of the following aria tags are below:

Resources & Credits

This guide was created with the help of many great resources. Below is a curated list of sites to check out.