All notes

Good References


Three ways to insert CSS

External stylesheet

<link rel="stylesheet" type="text/css" href="mystyle.css">

Internal stylesheet

body {
    background-color: linen;

h1 {
    color: maroon;
    margin-left: 40px;

Inline styles

<h1 style="color:blue;margin-left:30px;">This is a heading</h1>


Relative Lengths:

em	Relative to the font-size of the element (2em means 2 times the size of the current font)
ex	Relative to the x-height of the current font (rarely used)
ch	Relative to width of the "0" (zero)
rem	Relative to font-size of the root element
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

Absolute Lengths:

cm	centimeters
mm	millimeters
in	inches (1in = 96px = 2.54cm)
px	pixels (1px = 1/96th of 1in)
pt	points (1pt = 1/72 of 1in)
pc	picas (1pc = 12 pt)

Pixels (px) are relative to the viewing device. For low-dpi devices, 1px is one device pixel (dot) of the display. For printers and high resolution screens 1px implies multiple device pixels.



WARNING: IE doesn't support it! And Firefox has some problem with it!

The appearance property is used to display an element using a platform-native styling based on the users' operating system's theme.

css-tricks: appearance.

.thing {
   -webkit-appearance: value;
   -moz-appearance:    value;
   appearance:         value;

// inputs with a type=search in WebKit browsers by default have rounded corners and are very strict in what you can alter via CSS. If you don't want that styling, you can remove it in one fell swoop with appearance.

input[type=search] {
  -webkit-appearance: none;

// Or you could take a input with type=text and just make it look like a search input:

input[type=text] {
  -webkit-appearance: searchfield;



By default, a background-image is placed at the top-left corner of an element, and repeated both vertically and horizontally.

The background of an element is the total size of the element, including padding and border (but not the margin).

Always set a background-color to be used if the image is unavailable.

// Sets two background images for the <body> element. Let the first image appear only once (with no-repeat), and let the second image be repeated:

body {
    background-image: url("img_tree.gif"), url("paper.gif");
    background-repeat: no-repeat, repeat;
    background-color: #cccccc;

Sets a linear-gradient (two colors) as a background image for a <div> element:

#grad1 {
    height: 200px;
    background-color: #cccccc;
    background-image: linear-gradient(red, yellow); // From red to yellow.

#grad1 {
    height: 200px;
    background-color: #cccccc;
    background-image: linear-gradient(red, yellow, green); // From red to yellow, then to green.

#grad1 {
    height: 200px;
    background-color: #cccccc;
    background-image: repeating-linear-gradient(red, yellow 10%, green 20%); // red-yellow accounts for 10% height, r-y-g accounts for 20% height, then repeat, which means it has 5 copies (5 x 20% = 100%).

#grad1 {
    height: 200px;
    background-color: #cccccc;
    background-image: radial-gradient(red, yellow, green); // Radial. Same as linear.


cover   Resize the background image to cover the entire container, even if it has to stretch the image or cut a little bit off one of the edges.
contain Resize the background image to make sure the image is fully visible.


html {
  background: url(greatimage.jpg);
  background-size: 300px 100px; 

html {
  background: url(greatimage.jpg), url(wonderfulimage.jpg);
  background-size: 300px 100px, cover;
  /* first image is 300x100, second image covers the whole area */


The clear property specifies which side(s) of an element other floating elements are not allowed.

clear: none(default)|left|right|both|initial|inherit.


content: normal|none|counter|attr|string|open-quote|close-quote|no-open-quote|no-close-quote|url|initial|inherit;

Example: attr

/* <a href="">W3Schools</a> will becomes:
W3Schools (
a:after {
  content: " (" attr(href) ")";

Example: counter

div {
  counter-reset: myIndex;

p {
  counter-increment: myIndex;

p:before {

counter-reset, counter-increment

counter-increment: none|id|initial|inherit;
  The default increment is 1.
  0 or negative values, are allowed.
counter-reset: none|name number|initial|inherit;
  The default reset value is 0.

/* Auto numbering on headings. */
h1 {
  counter-reset: h2;
h2 {
  counter-reset: h3;
h3 {
  counter-reset: h4;
h4 {
  counter-reset: h5;

h2:before {
  counter-increment: h2;
  content: counter(h2) ". ";
h3:before {
  counter-increment: h3;
  content: counter(h2)"." counter(h3) ". ";
h4:before {
  counter-increment: h4;
  content: counter(h2)"." counter(h3)"." counter(h4) ". ";
h5:before {
  counter-increment: h5;
  content: counter(h2)"." counter(h3)"."counter(h4)"." counter(h5) ". ";


It controls what the mouse cursor will look like when it is located over the element in which this property is set.

css-tricks: cursor.

.auto            { cursor: auto; }
.default         { cursor: default; }
.none            { cursor: none; }

.context-menu    { cursor: context-menu; }
.help            { cursor: help; }
.pointer         { cursor: pointer; }
.progress        { cursor: progress; }
.wait            { cursor: wait; }
.cell            { cursor: cell; }
.crosshair       { cursor: crosshair; }
.text            { cursor: text; }
.vertical-text   { cursor: vertical-text; }
.alias           { cursor: alias; }
.copy            { cursor: copy; }
.move            { cursor: move; }
.no-drop         { cursor: no-drop; }
.not-allowed     { cursor: not-allowed; }
.all-scroll      { cursor: all-scroll; }
.col-resize      { cursor: col-resize; }
.row-resize      { cursor: row-resize; }
.n-resize        { cursor: n-resize; }
.e-resize        { cursor: e-resize; }
.s-resize        { cursor: s-resize; }
.w-resize        { cursor: w-resize; }
.ns-resize       { cursor: ns-resize; }
.ew-resize       { cursor: ew-resize; }
.ne-resize       { cursor: ne-resize; }
.nw-resize       { cursor: nw-resize; }
.se-resize       { cursor: se-resize; }
.sw-resize       { cursor: sw-resize; }
.nesw-resize     { cursor: nesw-resize; }
.nwse-resize     { cursor: nwse-resize; }

// You can also have the cursor be an image:
.custom {
  cursor: url(images/my-cursor.png), auto;



The value "none" lets you turn off the display of an element; when you use "none", all descendant elements also have their display turned off. The document is rendered as though the element doesn't exist in the document tree.

flex, inline-flex

css-tricks: A guide to flexbox.


How to center a div


//---------- text-align center the outer
#outer {
  width: 100%;
  text-align: center;
#inner {
  display: inline-block;

//---------- display table the inner
// If you can't add text-align to the outer, then you have to make the inner a table:
#inner {
  display: table;
  margin: 0 auto;


none	Defines a normal text. This is default.
underline 	Defines a line below the text.
overline 	Defines a line above the text.
line-through 	Defines a line through the text.
initial		Sets this property to its default value.
inherit		Inherits this property from its parent element.


.ellipsis {
  text-overflow: ellipsis;

  /* Required for text-overflow to do anything */
  white-space: nowrap;
  overflow: hidden;

Note that text-overflow only occurs when the container's overflow property has the value "hidden, scroll or auto" and "white-space: nowrap;".




The border-collapse property is for use on "table" or "table-like" elements.

separate (default) - in which all table cells have their own independent borders and there may be space between those cells as well.
collapse - in which both the space and the borders between table cells collapse so there is only one border and no space between cells.

table {
  border-collapse: separate; /* Or do nothing, this is default */
  border-spacing: 3px; /* Only works if border-collapse is separate */

How to collapse/merge div borders

SO. "border-collapse" is only used in tables. Here is the method for divs:

div {
  // Here is how it works: first float, then -1px the margin.
  margin-left: -1px;
  margin-top: -1px;

  // This is only for visualisation.
  border:1px solid tomato;


none 	Default value. No shadow is displayed
h-shadow 	Required. The position of the horizontal shadow. Negative values are allowed
v-shadow 	Required. The position of the vertical shadow. Negative values are allowed
blur 	Optional. The blur distance.
spread 	Optional. The size of shadow.
color 	Optional. The color of the shadow. The default value is black.
inset 	Optional. Changes the shadow from an outer shadow (outset) to an inner shadow.

Note: In Safari (on PC) the color parameter is required. If you do not specify the color, the shadow is not displayed at all.

box-sizing box-sizing.

The current versions of all browsers use the original "width or height + padding + border = actual width or height" box model. With box-sizing: border-box;, we can change the box model to what was once the "quirky" way ( IE has done the box model right), where an element's specified width and height aren't affected by padding or borders. This has proven so useful in responsive design that it's found its way into reset styles.

Universal reset:

html {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
*, *:before, *:after {
  -webkit-box-sizing: inherit;
  -moz-box-sizing: inherit;
  box-sizing: inherit;

flex related

The main idea behind the flex layout is to give the container the ability to alter its items' width/height (and order) to best fill the available space (mostly to accommodate to all kind of display devices and screen sizes). A flex container expands items to fill available free space, or shrinks them to prevent overflow.

Most importantly, the flexbox layout is direction-agnostic as opposed to the regular layouts (block which is vertically-based and inline which is horizontally-based). While those work well for pages, they lack flexibility (no pun intended) to support large or complex applications (especially when it comes to orientation changing, resizing, stretching, shrinking, etc.). ````

Properties for the Parent

.container {
  display: flex; /* or inline-flex */

  flex-direction: row | row-reverse | column | column-reverse;
  flex-wrap: nowrap | wrap | wrap-reverse; /* By default, flex items will all try to fit onto one line. You can change that and allow the items to wrap as needed. */
  flex-flow: <‘flex-direction’> || <‘flex-wrap’>; /* a shorthand flex-direction and flex-wrap properties. */

  justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly; /* defines the alignment along the main axis. */
  align-items: flex-start | flex-end | center | baseline | stretch; /* defines the default behaviour for how flex items are laid out along the cross axis. "center" will align by the center of children; "baseline" will align by the text baseline of children. "stretch" will make children occupy the whole hight. */
  align-content: flex-start | flex-end | center | space-between | space-around | stretch; /* This aligns a flex container's lines within when there is more than one lines in the cross-axis. */



flex-start (default): items are packed toward the start line
flex-end: items are packed toward to end line
center: items are centered along the line

space-between: items are evenly distributed in the line; first item is on the start line, last item on the end line
space-around: items are evenly distributed in the line with equal space around them
space-evenly: items are distributed so that the spacing between any two adjacent alignment subjects, before the first alignment subject, and after the last alignment subject is the same

.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;
  display: flex;

.flex-start { 
  justify-content: flex-start; 

<ul class="flex-container flex-start">
  <li class="flex-item">1</li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>



It helps aligning a flex container's lines within it when there is extra space in the cross-axis (e.g. y-axis), similar to how justify-content aligns individual items within the main-axis (e.g. x-axis).

This property has no effect when the flexbox has only a single line.

stretch (default): lines stretch to take up the remaining space
flex-start: lines packed to the start of the container
flex-end: lines packed to the end of the container
center: lines packed to the center of the container
space-between: lines evenly distributed; the first line is at the start of the container while the last one is at the end
space-around: lines evenly distributed with equal space between them

Properties for the Children: order, flex-grow

.item {
  order: <integer>; /* Default is 0. By default, flex items are laid out in the source order. */
  flex-grow: <number>; /* default 0. If all items have flex-grow set to 1, the remaining space in the container will be distributed equally to all children. */
  flex-shrink: <number>; /* default 1. This defines the ability for a flex item to shrink if necessary. */
  flex-basis: <length> | auto; /* default auto. This defines the default size of an element before the remaining space is distributed. It can be a length (e.g. 20%, 5rem, etc.) or a keyword. */
  flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]; /* Shorthand for flex-grow, flex-shrink and flex-basis combined. Default is 0 1 auto. It is recommended that you use this shorthand property rather than set the individual properties. The short hand sets the other values intelligently. */
  align-self: auto | flex-start | flex-end | center | baseline | stretch; /* allows the default alignment (or the one specified by align-items) to be overridden for individual flex items. */

margin margin.

// To center something horizontally in modern browsers, you can use
display: flex;
justify-content: center;
box-sizing: border-box;
width: 100%;

// However, in older browsers like IE8-9 that do not support Flexible Box Layout, these are not available. In order to center an element inside its parent, use
margin: 0 auto;
box-sizing: border-box;
width: 100%;


auto: The browser selects a suitable margin to use. For example, in certain cases this value can be used to center an element.

wcfNote: when a div has "margin: auto", it may have a longer width than its parent.

Margin collapsing

Elements' top and bottom margins are sometimes collapsed into a single margin that is equal to the larger of the two margins.




It's similar to border except that:

It is often used for accessibility reasons, to emphasize a link when tabbed to without affecting positioning and in a different way than hover.

a:focus {
  outline-width: 1px;
  outline-style: dashed;
  outline-color: red;

overflow, controls the scroll-bar

visible	The overflow is not clipped. It renders outside the element's box. This is default.
hidden	The overflow is clipped, and the rest of the content will be invisible
scroll	The overflow is clipped, but a scroll-bar is added to see the rest of the content
auto	If overflow is clipped, a scroll-bar should be added to see the rest of the content

.box {
  overflow-y: hidden;
  overflow-x: scroll;

Scroll bar shows only when user hover over on Mac OS

Float Clearing

One of the more popular uses of setting overflow, strangely enough, is float clearing. The element with overflow (any value except visible) will extend (instead of collapsing) as large as it needs to encompass floated child elements inside, assuming that the height isn't declared. float clearing.

A better float clearing technique is the clearfix, as it doesn't require you to alter the overflow property in a way you don't need.


The Clearfix: Force an Element To Self-Clear its Children.

css-tricks: clear-fix.

.group:after {
  content: "";
  display: table;
  clear: both;

<div class="group">
  <div class="is-floated"></div>
  <div class="is-floated"></div>
  <div class="is-floated"></div>

You would use this instead of clearing the float with something like <br style="clear: both;" />at the bottom of the parent (easy to forget, not handleable right in CSS, non-semantic) or using something like overflow: hidden; on the parent (you don't always want to hide overflow).

Generating block formatting context

It’s interesting to note that overflow will also create a new block formatting context which is useful if we want to align a block element next to a floated one. css-tricks.


The transform property allows you to visually manipulate an element by skewing, rotating, translating, or scaling.

scale(): affects the size of the element. This also applies to the font-size, padding, height, and width of an element, too. It’s also a a shorthand function for the scaleX and scaleY functions.
skewX() and skewY(): tilts an element to the left or right, like turning a triangle into a parallelogram. There is no shorthand skew property.
translate(): moves an element sideways or up and down.
rotate(): rotates the element clockwise from its current position.
matrix(): a function that is probably not intended to be written by hand, but combines all transforms into one.
perspective(): doesn’t affect the element itself, but affects the transforms of descendent elements' 3D transforms, allowing them all to have a consistent depth perspective.

//---------- This makes an animation that translates a box back and forth

.square {
  height: 100px;
  width: 100px;
  background-color: #3d9970;
  display: flex;
  text-align: center;
  justify-content: center;
  align-content: center;
  color: white;
  padding: 5px;
  animation: shimmy 3s infinite;
  animation-direction: alternate;

@keyframes shimmy {
  0% {
    transform: translate(0, 0);    
  100% {
    transform: translate(20px, 50px);

//---------- Others

.element {
  transform: rotate(25deg);
} css transform.

It modifies the coordinate space of the CSS visual formatting model.


The user-select property in CSS controls how the text in an element is allowed to be selected. For example, it can be used to make text unselectable, so that the reader can't copy and paste.

user-select: auto / all / none;


vertical-align, inline-blocks and line-height provides a very good example demoing the different effects of inline-blocked "span"s with different "vertical-align".


top and bottom should always touch the box horizontal borders.

width, min-width, max-width

MozillaDeveloper: CSS-width.

The width CSS property specifies the width of the content area of an element. The content area is inside the padding, border, and margin of the element.

The max-width property overrides the width property, but min-width will always override max-width. So the precedence: min-width, max-width, width.

height: auto

In Bootstrap, height: auto; is used in .img-responsive, so that the image preserve its aspect-ratio when scaling.

.img-responsive {
  display: block;
  max-width: 100%;
  height: auto;


normal 	Default value. Break words according to their usual rules.
break-all 	Lines may break between any two letters.
keep-all  	Breaks are prohibited between pairs of letters.

Normally, line breaks in text can only occur in certain spaces, like when there is a space or a hyphen.

In the example below we can make the word-break between letters instead:

p {
  word-break: break-all;

If we then set the width of the text to one em, the text line will become a vertical text line.

This value is often used in places with user generated content so that long strings don't risk breaking the layout. One very common example is a long copy and pasted URL. If that URL has no hyphens, it can extend beyond the parent box and look bad or worse, cause layout problems.

This property is also often used in conjunction with the hyphens property so that when breaks occur a hypen is inserted, as per the standard in books.

// The full usage, with needed vendor prefixes, is:

 -ms-word-break: break-all;
     word-break: break-all;

     /* Non standard for WebKit */
     word-break: break-word;

-webkit-hyphens: auto;
   -moz-hyphens: auto;
        hyphens: auto;

word-break vs word-wrap

word-wrap: break-word: will wrap long words onto the next line, and adjusts different words so that they do not break in the middle.

word-break: break-all: irrespective of whether it’s a continuous word or many words, breaks them up at the edge of the width limit. (i.e. even within the characters of the same word).

word-wrap, overflow-wrap

word-wrap: break-word recently changed to overflow-wrap: break-word.

normal 	Break words only at allowed break points
break-word 	Allows unbreakable words to be broken

pre tag not affected by word-wrap:break-word?


pre {
	white-space: pre-wrap;		 /* CSS 3 */
	white-space: -moz-pre-wrap;	 /* Mozilla, since 1999 */
	white-space: -pre-wrap;		 /* Opera 4-6 */
	white-space: -o-pre-wrap;	 /* Opera 7 */
	word-wrap: break-word;		 /* Internet Explorer 5.5+ */

To be more browser robust, use the following: Reference

-ms-word-break: break-all;
/* Be VERY careful with this, breaks normal words wh_erever */
word-break: break-all;
/* Non standard for webkit */
word-break: break-word;
-webkit-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;


normal 	Sequences of whitespace will collapse into a single whitespace. Text will wrap when necessary. This is default.
nowrap 	Sequences of whitespace will collapse into a single whitespace. Text will never wrap to the next line.
pre 	Whitespace is preserved by the browser. Text will only wrap on line breaks. Acts like the pre tag in HTML.
pre-line 	Sequences of whitespace will collapse into a single whitespace. Text will wrap when necessary, and on line breaks.
pre-wrap 	Whitespace is preserved by the browser. Text will wrap when necessary, and on line breaks .



none	Words are never hyphenated at at line breaks.
manual	Words are only broken at line breaks where there are characters inside the word that suggest line break opportunities.
auto	Words can be broken at appropriate hyphenation points either as determined by hyphenation chars or as determined automatically by a language-appropriate hyphenation resource (if supported by the browser or provided via @hyphenation-resource).
The hyphenation chars for manual breaks are

Positions: relative, fixed, absolute

static. The default. Any element with static position is said to be not positioned, otherwise is said to be positioned.

relative. The element is adjusted away from its normal position by setting top, right, bottom, left properties. See example below.
Other contents will not take its place, e.g. a relative element holds its place. This makes "relative" appear not very useful, but it performs an important task: setting ancestral container for "absolute" element. See example below.

fixed. The element is positioned relative to the viewport. It does not leave a gap, in other words, its element will not occupy a position in normal flow.

absolute. Behaves like fixed but relative to the nearest positioned ancestor. Remember, "absolute" is to "relative", but not "fixed". css positioning.

Relative example:

#div-1 {

If we set relative positioning on div-1, any elements within div-1 will be positioned relative to div-1. Then if we set absolute positioning on div-1a, we can move it to the top right of div-1.

#div-1 {
#div-1a {

/* If we float one column to the left, then also float the second column to the left, they will push up against each other. */
#div-1a {
#div-1b {

/* Then after the floating elements we can "clear" the floats to push down the rest of the content. */
#div-1c {

float and clear

Float is used to wrapping text around images, such as

img {
	float: right;
	margin: 0 0 1em 1em;

will put images on the right of its container, and the image has a margin with regards to surrounding text.

Sometimes when floated elements cause trouble to its followers, its followers could use clear to get rid of it. For example, the element following a left-floated div could use clear: left.



Grouping Selectors

h1 {
    text-align: center;
    color: red;
h2 {
    text-align: center;
    color: red;

/* Is the same as: */
h1, h2 {
    text-align: center;
    color: red;

Descendant selector


如果您希望只对 h1 元素中的 em 元素应用样式,可以这样写

h1 em {color:red;}

// Use a white space to match all descendants of an element:
div.dropdown * {
    color: red;

Child selector

如果您不希望选择任意的后代元素,而是希望缩小范围,只选择某个元素的子元素,请使用子元素选择器(Child selector)。Ref.

/* 选择只作为 h1 元素子元素的 strong 元素,可以这样写:*/
h1 > strong {color:red;}

/* 选择作为 td 元素子元素的所有 p 元素,这个 td 元素本身从 table 元素继承,该 table 元素有一个包含 company 的 class 属性。*/ td > p

// Use a white space to match all children of an element:
div.dropdown > * {
    color: red;

Q: is there any parent selectors?

StackOverflow: is there a css parent selector?.


jQuery: has-selector.

Format: jQuery( ":has(selector)" )

For example, the expression $( "div:has(p)" ) matches a "div" if a "p" exists anywhere among its descendants, not just as a direct child.
$( "div:has(p)" ).addClass( "test" );

CSS4 WD (not supported yet)

The Selectors Level 4 Working Draft includes a :has() pseudo-class that works the same as the jQuery implementation.

<!-- Select the <li> element that is a immediate parent of the anchor tag -->
li:has(> { /* styles to apply to the li tag */ }

Adjacent sibling selector

如果需要选择紧接在另一个元素后的元素,而且二者有相同的父元素,可以使用相邻兄弟选择器(Adjacent sibling selector)。Ref.

/* 例如,如果要增加紧接在 h1 元素后出现的段落的上边距,可以这样写:*/
h1 + p {margin-top:50px;}

General sibling selectors

Selects nodes that follow (not necessarily immediately) the former specified element, if both elements shared the same parent.

/* match all <span> elements that follow a <p> element inside the same element. */
p ~ span {}

Attribute selectors

Introduced in CSS2. Ref.

[attribute] 	选取带有指定属性的元素。
[attribute=value] 	The attribute has to have the exact value specified.
[attribute~=value] 	The attribute's value needs to be a whitespace separated list of words (for example, class="title featured home"), and one of the words is exactly the specified value.
[attribute|=value] 	The attribute's value is exactly "value" or starts with the word "value" and is immediately followed by "-", so it would be "value-".
[attribute^=value] 	The attribute's value starts with the specified value.
[attribute$=value] 	The attribute's value ends with the specified value.
[attribute*=value] 	The attribute's value contains the specified value.

/* 包含标题(title)的所有元素变为红色:*/
*[title] {color:red;}

/* 只对有 href 属性的锚(a 元素)应用样式: */
a[href] {color:red;}

/* 将同时有 href 和 title 属性的 HTML 超链接的文本设置为红色:*/
a[href][title] {color:red;}

/* 所有带有 alt 属性的图像应用样式,突出显示这些有效的图像。更适合用来诊断而不是设计。*/
img[alt] {border: 5px solid red;}

/* 将指向 Web 服务器上某个指定文档的超链接变成红色:*/
a[href=""] {color: red;}

/* 选择 class 属性中包含 important 的元素。如果忽略了波浪号,则说明需要完成完全值匹配。*/
p[class~="important"] {color: red;}
/* 可以匹配如下 */
<p class="important warning">This paragraph is a very important warning.

/* all the div elements that are posts */
div[class*="post"] {
  background-color: #333;

a[href$=".jpg"] {
  background: url(jpeg.gif) no-repeat left 50%;
  padding: 2px 0 2px 20px;
a[href$=".pdf"] {
  background: url(pdf.gif) no-repeat left 50%;
  padding: 2px 0 2px 20px;

CSS precedence

we sometimes have the tendency to litter our HTML with excessive and unnecessary classes and ids, divs and spans. The best way is using more complex CSS selectors, ones that can target specific elements without the need of a class or an id.

  1. Author > User > default.
  2. !important > normal.
  3. Specificity. Calculate as (a,b,c,d). See below for example.
    1. Inline style
    2. ID
    3. class, pseudo class, attribute selectors (li[id=red]).
    4. element, pseudo element
  4. Latter > earlier.

A good reference.

override with !important

td {height: 100px !important}

Calculate specificity

p: 1 element - (0,0,0,1)
div: 1 element - (0,0,0,1)
#sidebar: 1 id - (0,1,0,0)
div#sidebar: 1 element, 1 id - (0,1,0,1)
div#sidebar p: 2 elements, 1 id - (0,1,0,2)
div#sidebar 2 elements, 1 class, 1 id - (0,1,1,2)

div {font-size: 14px} - (0,0,1,2)
#sidebar p {font-size: 12px} - (0,1,0,1)



A CSS comment is deliminated by /* and */. The comment can span multiple lines.


sitePoint: setting body width.

"margin: auto;" only works if you have a valid DOCTYPE declaration on top of your page. See this like for why doctype is so important.

This will work in every browser except for IE5/Windows. If you want it to work there, you have to wrap another "div" around #content and give it the CSS property of "text-align: center;".

#content {
  width: 600px;
  margin-left: auto;
  margin-right: auto;

Set width and centered

stackOverflow: best way to make the body max-width and centered.

html {
    margin:    0 auto;
    max-width: 900px;
    /* whatever you want */

HTML and its fonts

Font names

There are two types of font family names:

When setting font-family, always start with the font you want, and end with a generic family name so that the browser could fall back on it. Example:

body {
	font-family: courier, sans-serif, monospace;

TT, teletype, monospace

Reference. The TT tag specifies that the enclosed text must be rendered in a teletype/monospaced font. The tag is not supported in HTML5, so use CODE etc instead.

Other similar tags include:

EM, emphasized text, italics

Although usually EM has the same effect as I, the two must be used non-interchageably: I specifies directly the italic font, while EM indicates that its enclosed text must be emphasized. EM must be rendered differently from STRONG (strongly emphasized text, usually rendered in bold). Other similar tags include:


The CSS white-space could be:

The CSS-trics page explains well the relationships of pre, pre-wrap and pre-line, and it gives an excellent summary table. This page give a good example.

Media query

Width. This is probably the most important property, since it can be used to choose page layout - less columns for narrower screens and more columns for wider ones. The property accepts min/max prefixes, so we'd better add those to specify a width range.

<link rel="stylesheet" media="print and (min-width:25cm)" href="a.css" /> <!-- In HTML -->

/* In CSS. The {...} only works when the 3 conditions are met. */
@media screen and (min-width: 400px) and (max-width: 700px) {}

/* In CSS. Import the CSS file only when either the two conditions are met: screen and (min-width: 400px), */
/* or projection and (color). The comma denotes an 'or' logic. */
@import url(example.css) screen and (min-width: 400px), projection and (color);

Orientation. There are two values for this property: portrait an landscape. It is easy to distinguish: when the height is larger than or equal to the width, it's portrait, otherwise landscape.

@media all and (orientation:portrait) {...}

Color. It accepts min/max prefixes. Its value type is integer, which specifies the bit number per color component of the device. If the device is not color device, the value is 0. The example below express a style for all color devices.

@media all and (color) { … }
@media all and (min-color: 1) {...}

Box model

The width

As defined in box model, the width of an element is just the width of its content. When designing a layout, its padding and border width may cause the mis-alignment. For such an element as follows, its box has a visual width of 210px:

p#big {
	width: 100px;
	border: 10px;
	padding: 100px;

In order to add the counting of padding and border width into the box width, we can set the following:

* {
  -webkit-box-sizing: border-box;
     -moz-box-sizing: border-box;
          box-sizing: border-box;

Then when we set an element with width equal to 200px, its total box width is 200px. Go to for reference.

calc in css3

In CSS3 there comes a powerful tool: calc. It supports these operators: "+ - * /". Example:

width: calc(100% - 2px*2);
Note that the two operators "+ -" must be surrounded by spaces, so this is wrong:
width: calc(100%-2px*2);


An example. When you hover the mouse on the div element, the transition takes effect.

div {
	transition:width 2s;
	-moz-transition:width 2s; /* Firefox 4 */
	-webkit-transition:width 2s; /* Safari and Chrome */
	-o-transition:width 2s; /* Opera */

div:hover {


All elements has a default z-index of 0. The element with lower z-index is beneath those with higher z-index. wcfNote: imagine z-index as a z-axis, pointing upwards to the readers.

Note: z-index only works on positioned elements (position:absolute, position:relative, or position:fixed).

Pseudo classes/elements

Pseudo class has the format: "element:pClassName". Pseudo element has the format: "element::pElementName".

Selector Example Example description
:link a:link Selects all unvisited links
:visited a:visited Selects all visited links
:active a:active Selects the active link
:hover a:hover Selects links on mouse over
:focus input:focus Selects the input element which has focus
::first-letter p::first-letter Selects the first letter of every <p> element
::first-line p::first-line Selects the first line of every <p> element
:first-child p:first-child Selects every <p> elements that is the first child of its parent
::before p::before Insert content before every <p> element
::after p::after Insert content after every <p> element
:lang(language) p:lang(it) Selects every <p> element with a lang attribute value starting with "it"

Use :before/:after on an input field

SO: use :before/:after on an input field.

:after and :before are not supported in Internet Explorer 7 and under, on any elements.

It's also not meant to be used on replaced elements such as form elements (inputs) and image elements.

In other words it's impossible with pure CSS.

However if using jquery you can use

$(".mystyle").after("add your smiley here");

Furthur explanation

:after and :before pseudo elements, they can only be put on container elements. Why? Because they are appended inside that particular element. "input" is not a container. "button" for instance is hence you can put them on. Specification actually says: before and after an element's document tree content It explicitly says CONTENT. So an element must be a container.