Skip to content

Instantly share code, notes, and snippets.

@vbwx
Last active May 3, 2019 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vbwx/4f4598bbf17bde96e36e70a0d4c39893 to your computer and use it in GitHub Desktop.
Save vbwx/4f4598bbf17bde96e36e70a0d4c39893 to your computer and use it in GitHub Desktop.
Development cheat sheets

Pseudocode Syntax

  • Alternatives are written as §{101¦202¦303}. Single alternative characters don’t need braces: a¦b¦c
  • Optional parts are written as §[option].
  • Optional alternatives can be written like §[101¦202¦303].
  • To improve legibility, a leading vertical bar is ignored.
§{
¦ choice 1
¦ choice 2
}
  • Variables are written as §var or §(var). (Only letters, numbers and underscores are valid names.)
  • Variable expressions are written like §(var*2).
  • §a¦§b is shorthand for §{§a¦§b}.
  • Expressions can also contain default values: §(var¦some default value)

Accessibility

Text contrast

Difference in luminance of text and background color must be at least 0.5; ideal is 0.75.

luminance = 0.299 * red + 0.587 * blue + 0.114 * green

Shortcuts for links & buttons

<a href="§uri" accesskey="§char"></a>

AppleScript

-- Run a command in a new Terminal window
tell application "Terminal" to do script "cd §directory";
-- Send an application window to the Dock
tell application "§app" to set miniaturized of window §number to true

CSS

Vertical centering

body {
  position: relative;
  min-height: §h;
  min-width: §w;
}
.container {
  position: absolute;
  height: §h;
  width: §w;
  left: 50%;
  top: 50%;
  margin-top: §(-h/2);
  margin-left: §(-w/2);
}

Footer at the bottom of the viewport

<body>
  <div class="container">
    <div class="content"></div>
    <div class="footer"></div>
  </div>
</body>
html, body {
  height: 100%;
}
.container {
  min-height: 100%;
  position: relative;
}
.content {
  padding-bottom: §h;
}
.footer {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: §h;
}

Vertical centering with variable height

html, body {
  height: 100%;
  width: 100%;
}
html {
  display: table;
}
body {
  display: table-cell;
  vertical-align: middle;
}
.container {
  width: §w;
  margin: 0 auto;
}

Horizontal centering

§selector {
  margin: 0 auto;
  width: §w;
}

Asymmetrical horizontal margin

* {
  margin: 0;
  padding: 0;
}
body {
  height: 100%;
  padding-right: §w;
}
.container {
  width: §w;
  margin-left: 33%;
}

Three-column layout

.left {
  float: left;
  width: §wl;
}
.right {
  float: right;
  width: §wr;
}
.middle {
  margin-left: §wl;
  margin-right: §wr;
}

Containing floats (micro clearfix)

.container {
  zoom: 1;
}
.container::before, .container::after {
  content: "";
  display: table;
}
.container::after {
  clear: both;
}
.container img {
  float: left;
}

HR tag as clearfix

hr {
  clear: both;
  height: 0.1px;
  border: none;
  visibility: hidden;
  margin: 0;
  padding: 0;
}

Block formatting context

  • Clear is only applied within this context
  • Contains floats
  • Isn't affected by outside floats
float: §{left¦right};
overflow: §{scroll¦auto¦hidden};
display: §{table¦table-cell¦inline-block};
position: §{absolute¦fixed};

Vertical centering of inline elements

h1 {
  height: §h;
  line-height: §h;
}

Uniform distribution of inline-blocks

<div class="container">
  <img ><img ><img >
  <span></span>
</div>
.container {
  text-align: justify;
  width: 100%;
}
.container > img {
  margin: §m;
  vertical-align: middle;
}
.container > span {
  display: inline-block;
  padding-left: 100%;
}

Drop-down menu

ul {
  list-style-type: none;
}
li {
  float: left;
}
li:hover {
  position: relative;
}
li:hover ul {
  top: §h;
  left: §l;
}
ul ul {
  z-index: 1;
  position: absolute;
  left: -110%;
  width: auto;
}

Shrink-to-fit

  • No width
  • Sets hasLayout
position: §{absolute¦fixed};
float: §{left¦right};
display: inline-block;
display: §{table¦inline-table¦table-cell}; /* not in IE < 8 */

Styling tables

table {
  table-layout: fixed;
  border-collapse: collapse;
}
caption {
  caption-side: bottom;
  margin: §m;
  text-align: §ta;
}
th, td {
  padding: §p;
  font-weight: normal;
}
thead {
  background: §bg1;
  border-bottom: §bb1;
}
tbody {
  background: §bg2;
}
th {
  color: §c;
}
th[scope=row] { … }
th[scope=col] { … }
tbody {
  border-bottom: §bb2;
}
§[ tbody tr:hover { … } ]

Media-specific styling

  • No footers & headers in print
  • Avoid HTML in e-mails! Only table layouts and inline styles are consistently supported. Always offer a text/plain alternative.
<link media="all and (max-width: §w)" src="§uri">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@media screen, projection {
  …
}
@media print {
  a[href*="://"]::after {
    content: " [" attr(href) "]";
  }
}
@media only screen and (max-device-width: §w) {
  …
}
@media only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (min-resolution: §r) { /* such as 192dpi */
  background-image: url("§file@2x.png");
}

Font embedding

@font-face {
  font-family: §name;
  src: url("§file.eot"); /* IE */
  src: local("!skip!"),
    url(§file.eot?#iefix) format(embedded-opentype),
    url(§file.woff) format(woff),
    url(§file.ttf) format(truetype),
    url(§file.svg) format(svg);
  font-weight: §{normal¦bold};
  font-style: §{normal¦italic};
}

Image replacement

.ir {
  background-color: transparent;
  border: 0;
  overflow: hidden;
  white-space: nowrap;
  text-indent: -9999px;
}
.ir:before {
  content: "";
  display: block;
  width: 0;
  height: 150%;
}

Invisible but accessible/focusable elements

.accessible {
  border: 0;
  overflow: hidden;
  padding: 0;
  margin: -1px;
  position: absolute;
  left: -9999px;
  top: auto;
  width: 1px;
  height: 1px;
}
.accessible.focusable:active,
.accessible.focusable:focus {
  clip: auto;
  height: auto;
  margin: 0;
  overflow: visible;
  position: static;
  width: auto;
}

Input element styling

input[type=text] {
  -webkit-appearance: §{none¦caret}; /* Safari & Chrome */
  -moz-apperance: §{none¦caret}; /* Firefox */
}
select::-ms-expand {
  display: none; /* IE >= 9 */
}

Input placeholder styling

/* Don’t group these selectors! */
::-webkit-input-placeholder { color: §c; }
:-moz-placeholder { color: §c; } /* Necessary for older versions */
::-moz-placeholder { color: §c; }
:-ms-input-placeholder { color: §c; }

Background color of autofilled fields

input[type=text]:-webkit-autofill { /* Safari & Chrome */
  -webkit-box-shadow: 0 0 0 1000px §color inset;
}
input[type=text]:-moz-autofill { /* Firefox */
  background-color: §color;
}

Hide button focus ring

input[type=button], button {
  outline: none;
}
input[type=button]::-moz-focus-inner, button::-moz-focus-inner { /* Firefox */
  border: 0;
}
input[type=button]:focus, button:focus
§[, input[type=button]:active, button:active ]
§[, input[type=button]:hover, button:hover ] {
  …
}

Text selection styling

::selection {
  background: §bg;
  color: §fg;
}

Advanced text styling

§selector::first-line { … }
§selector::first-letter { … }

Link styling

a {
  text-decoration: none;
}
a:link, a:visited { … }
a:focus, a:hover, a:active { … }
a:active {
  text-decoration: underline;
}

Toggle visibility (accordion without JavaScript)

<div class="toggle">
  <input type="checkbox" value="1" id="§c_id">
  <label for="§c_id"></label>
  <div role="toggle"></div>
</div>
.toggle > label {
  cursor: pointer;
}
.toggle > label::before {
  content: "+ "; /* for demonstration purposes */
}
.toggle > input {
  display: none;
}
.toggle > input:not(:checked) ~ [role=toggle] {
  display: none;
}
.toggle > input:checked ~ [role=toggle] {
  display: block;
}
.toggle > input:checked ~ label::before {
  content: "– ";
}

Vertical align

Only applies to elements with one of these display values:

  • table-cell
  • inline
  • inline-block

Specific to Mobile Safari

body {
  -webkit-text-size-adjust: 100%;
}

Specific to Internet Explorer

/* Necessary rules */
thead {
  display: table-header-group;
}
tfoot {
  display: table-footer-group;
}
img {
  width: auto; /* for IE 8 on Win XP */
}
/* Triggering hasLayout */
§selector {
  §{
  ¦ zoom: 1; /* No block formatting context */
  ¦ float: §{left¦right};
  ¦ display: inline-block;
  ¦ position: absolute;
  ¦ overflow: §{hidden¦scroll¦auto};
  }
}
/* Opacity for all IE versions */
§selector {
  opacity: §v;
  filter: progid:DXImageTransform.Microsoft.Alpha(opacity=§(v*100));
  zoom: 1;
}
/* Avoid clipping with negative margins */
§selector { position: relative; }
/* Float-drop solution */
§selector { float: left; }
§selector { margin-right: -3px; }
/* required for links inside hovered elements, e.g., <li><a>…</a></li> */
§selector:hover { background-position: 0 0; }
/* Support for CSS3 decorations (http://css3pie.com) */
§selector {
  border-radius: §r;
  …
  behavior: url(§path/PIE.htc); /* relative to the document */
}
/* calc() for IE < 9 */
§selector {
  width: expression(§js);
}

HTML

Sensible tags in head

<meta charset="§(cs¦utf-8)">
§[<meta name="keywords" content="">]
§[<meta name="description" content="">]
<meta name="viewport" content="">
<meta property="og:§{title¦type¦url}" content="">
<meta property="og:image§[:§{url¦secure_url¦type¦width¦height}]" content="">
§[<meta property="og:video§[:§{url¦secure_url¦type¦width¦height}]" content="">]
§[<meta property="og:audio§[:§{url¦secure_url¦type}]" content="">]
§[<meta property="og:§{description¦determiner¦locale§[:alternate]¦site_name}" content="">]

Table structure

<table>
  <thead>
    <tr><th scope="col">Column 1</th><th scope="col">Column 2</th></tr>
  </thead>
  <tbody>
    <tr><td>1</td><td>2</td></tr></tbody>
  <caption>Table description</caption>
</table>

Special entities

&zwnj; <!-- invisible entity -->

Specific to Internet Explorer

  • No whitespace between </li> and following <li>
  • Avoid HTML comments in general (they can trigger rendering bugs)
<!--[if lt IE 7]><body class="ie ie6"><![endif]-->
<!--[if IE 7]><body class="ie ie7"><![endif]-->
<!--[if IE 8]><body class="ie ie8"><![endif]-->
<!--[if IE 9]><body class="ie ie9"><![endif]-->
<!--[if gte IE 10]><body class="ie ie10"><![endif]-->
<!--[if !IE]>--><body class="noie"><!--<![endif]-->

Graceful degradation

<video width="§w" controls poster="§poster_uri" §[src="§src_uri"]>
  <object >§[<param >]</object>
  §[ <source src="§src_uri" type="§mime"><source > ]
</video>

JavaScript

JSHint

/* jshint validthis:true */
/* global §variables */
/* jshint -W079 */

Module pattern

§Class.prototype.method = function() {
  var §private;
  return function() {
    
    return this.§member;
  };
}();

Iterating over properties

for (name in obj) {
  if (obj.hasOwnProperty(name)) {
    
  }
}

Iterating over array elements

var i, max;
for (i = 0, max = ary.length; i < max; i++) {
  
}

Callback pattern

function §f (callback) {
  
  if (typeof callback == 'function') {
    callback.call(§obj, §arg1, );
  }
  
}

Constructor pattern

var §Class = function (x) {
  if (this.constructor !== §Class) {
    return new §Class(x);
  }
  this.getX = function() {
    return x;
  };
  
};

Accounting for floating point arithmetic inaccuracy

x = 0.2;
y = 0.3;
z = 0.1;
equal = (Math.abs(x - y + z) < Number.EPSILON);

ECMAScript 2015

Mandatory parameters

let mandatory = () => { throw new Error("Missing parameter"); };
let §f = (§param = mandatory()) => {
  
};

Constants

const ary = [1, 2, 3];
for (const [index, elem] of ary.entries) {
  
}

Destructuring assignment

[a, b] = [b, a];

Interpolated strings

console.log(`value of property y: ${x.y}`);

Document Object Model

Communication between document and iframe

// From iframe
§{parent¦top}.§variable
// To iframe
document.getElementById(§iframe_id).contentWindow.§variable
// To iframe in different domain
var w = document.getElementById(§iframe_id).contentWindow;
w.postMessage(§data, §target_url);
// Implemented in iframe document, maybe also in parent document
function §handler (event) {
  if (ev.origin !== §src_url) return;
  /* do something with event.data */
  event.source.postMessage(§data, §src_url);
}
window.addEventListener("message", §handler, false);

Cross-browser error logging

try {
  
}
catch (e) {
  (console.error || console.log).call(console, e.message, e.stack || e);
}

PHP

HTTP headers for file transfer

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"'); //<<< Note the " " surrounding the file name
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));

Sass

Color functions

@function tint($color, $percentage) {
  @return mix($color, white, $percentage);
}
@function shade($color, $percentage) {
  @return mix($color, black, $percentage);
}

font-face mixin

@mixin font($family, $path, $file: $family, $weight: normal, $style: normal, $svgID: $file) {
  @font-face {
    font-family: $family;
    src: url("#{$path}/#{$file}.eot");
    src: local(''),
         url("#{$path}/#{$file}.woff") format('woff'),
         url("#{$path}/#{$file}.ttf") format('truetype'),
         url("#{$path}/#{$file}.svg##{$svgID}") format('svg');
    font-weight: $weight;
    font-style: $style;
  }
}

Browser compatibility mixins

@mixin pie { // For IE 6/7/8/9
  behavior: url(js/PIE.htc);
}
@mixin appearance($style: none) {
  -webkit-appearance: $style;
  -moz-appearance: $style;
  appearance: $style;
}
@mixin placeholder($color) {
  ::-webkit-input-placeholder {
    color: $color;
  }
  :-moz-placeholder {
    color: $color;
  }
  ::-moz-placeholder {
    color: $color;
  }
  :-ms-input-placeholder {
    color: $color;
  }
}
@mixin autofill-background($color) {
  input:-webkit-autofill {
    -webkit-box-shadow: 0 0 0px 1000px $color inset;
  }
  input:-moz-autofill {
    -moz-box-shadow: 0 0 0px 1000px $color inset;
  }
  input:-o-autofill {
    -o-box-shadow: 0 0 0px 1000px $color inset;
  }
}
@mixin box-shadow($style) {
  -webkit-box-shadow: $style;
  box-shadow: $style;
  @include pie;
}

Shell Commands

Git

# Commit all unstaged changes with a message
git commit -am §message
# Show what would be pushed
git push --dry-run
# Show list of changed/added/removed files
git diff --stat §branch §[HEAD]
# Show list of remote branches
git branch -r
# Check out a remote branch
git fetch && git checkout origin/§branch
# Show historical changes of a file
git log -p §file
# Reset the HEAD to the state of the remote branch
git reset §[--hard¦--merge] origin/§branch
# Reset the HEAD to the state of the last commit
git reset HEAD@{1}  # last commit
# Reset the HEAD to the nth parent of HEAD
git reset --hard §{HEAD~¦HEAD^§n}
# Discard all unstaged changes
git checkout -- .
# Alter the last commit before publishing it
git commit --amend
# Undo the changes of a commit (without rewriting history)
git revert §commit
# Publish a new branch to the remote
git push -u origin §branch
# Delete a branch from the remote
git push origin --delete §branch
# This might be necessary after editing gitignore
git rm -r --cached . && git add .
# Remove untracked files & directories
git clean -fd §[--dry-run]
# Merge two branches without autocommiting (optional)
git merge §[--no-commit] §branch
# When you don't want to fix conflicts
git merge --abort
# So you can type "git co develop" instead of "git checkout develop"
git config --global alias.co checkout
# Needed when you also use GitHub Desktop on macOS
git config --global credential.helper osxkeychain
# Compare commit with its parent
git diff §commit^!
# Push tags to remote
git push --tags
# Create a new branch that tracks a remote branch
git branch --set-upstream-to=origin/§branch §branch
# Transfer uncommited changes to another branch
git stash && git checkout §branch && git stash apply
# Show differences between stash and current branch
git stash show -p
# Copy changes to specific files from another branch
git checkout --patch §commit¦§branch §file
# Overwrite local files with files from remote branch
git fetch --all
git reset --hard origin/§branch
git pull origin §branch
# Clone new submodules into already existing repository
git submodule update --init --recursive

# Define Git Flow branch names
git flow init
# Features are branched from develop
git flow feature §{start¦publish¦pull origin¦finish} §name
# Features are merged into a release branch, which is also branched from develop
git flow release §{start¦publish¦finish} §version
# Hotfixes are branched from master
git flow hotfix §{start¦finish} §name

SVN

# Edit list of ignored files in a directory
svn propedit svn:ignore §dir
# Set ignored file in §dir
svn propset svn:ignore §file §dir
# Execute this when SVN can’t commit for no reason
svn update
# Show changes of a revision
svn log --verbose -r §revision

Bash

#!/bin/bash
# Strict mode
set -euo pipefail
IFS=$'\n\t'

# Check if a variable/array is defined and not empty
[[ ${var-} ]]
# Check if a variable is defined
# (An empty array is not recognized here!)
[[ ${var+1} ]]
# Check if a variable is defined as an array
[[ $(declare -p var 2> /dev/null) =~ "declare -a" ]]
# Access variable with dynamic name
varname=prefix_$suffix
echo "${!varname}"
# Reliably get the path to the directory that contains the current script
echo "$(dirname "$(readlink -f "$0")")"

Completion

brew install bash-completion  # requires Homebrew
# Simple completion of subcommands, etc.
complete -W §list_of_words §command  # only in bash, sh & csh

Mac Development

# Install Xcode command line tools
xcode-select --install
# Create an Apple icon file, given the following directory:
# (2x files are optional; not every resolution has to exist)
# App.iconset/
# ├── icon_16x16.png
# ├── icon_16x16@2x.png
# ├── icon_32x32.png
# ├── icon_32x32@2x.png
# ├── icon_128x128.png
# ├── icon_128x128@2x.png
# ├── icon_256x256.png
# ├── icon_256x256@2x.png
# ├── icon_512x512.png
# └── icon_512x512@2x.png
iconutil -c icns App.iconset
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment