CSS - Cheat sheet


How can we apply a style based on the data attribute?

[data-make-raw] { outline: 1px solid tomato; }

When style our link / anchor elements, how should we position the :link, :visited, :hover, and :active pseudo-classes?

In most cases your CSS for links need to be in the order :link :visited :hover :active.

CSS Shorthands

border: 1px solid #333;
color: #333;
margin: 5px 10px 10px 5px;  /* Top, Right, Bottom, Left (clockwise) */
padding: 5px 10px 10px 5px;
background: color image-url repeat attachment position;
background: #ccc url(logo.png) no-repeat 0px 0px fixed;
background: #f00 url(background.gif) no-repeat fixed 0 0;
font: [style] [variant] [weight] size families
font: font-style font-variant font-weight fond-size / line-height font-family
font:italic small-caps bold 1em/140% "Lucida Grande",sans-serif
// Acceptable values for font-style are: normal, italic, oblique or inherit
// Acceptable values for font-variant are: small-caps | normal | inherit
// Acceptable values for font-size are: xx-small, x-small, small, medium, large, x-large, xx-large, smaller, larger
// Acceptable values for font-weight: 
//   100 (ultra thin or ultra light)
//   200 (thin or light)
//   300
//   400 (normal)
//   500 (medium)
//   600 (semi-bold)
//   700 (bold)
//   800 (extra-bold)
//   900 (ultra-bold)
list-style:square inside url(image.gif);  /* list-style-type, list-style-position, list-style-image */

External stylesheet:

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

Internal stylesheet:

<style type="text/css">
hr {color: sienna}
p {margin-left: 20px}
body {background-image: url("images/back40.gif")}

Old browser that do not understand the style tag will render its content on the page. To avoid this, use an HTML comment as follow:

<style type="text/css">
hr {color: sienna}
p {margin-left: 20px}
body {background-image: url("images/back40.gif")}

Inline style

<p style="color: sienna; margin-left: 20px">
This is a paragraph


/* This is a comment */

Basic CSS:

selector {property: value}

The selector can be an HTML element / tag name, an ID, or a CSS class name. If the selector is an ID, it needs to be prefixed by #. If the selector is a CSS class name, it needs to be prefixed with a dot. The property is the attribute you wish to change, and each property can take a value. The property and value are separated by a colon, and surrounded by curly braces:

// Example of selector based on element or tag name:
body { color: black}
p { font-family: "sans serif" }
p { text-align: center; color:red }

// Example of selector based on ID:
#mydiv {color: green}

// Example of selector based on CSS class name:
.center {text-align: center}

// Example of selector based on attribute.  The name of the attribute is "type"
// and the value of the attribute is "text".  Note that we do not need to
// quote the name of the attribute, but we do need to quote the value
// of the attribute
input[type="text"] {background-color: blue}

// Special selectors:
* match any element
E match any element of type E (E is an HTML tag)
E F match any element of type F that is direct descendent of type E
E > F match any element of type F that is a child of element type E

How to make the width of an element collapse so that it is just enough to contain its content?

Float the element, or change its position to absolute and set the width to auto.

I was in a situation where I need to make a button (the text all appear on one line), but the length of the label vary. Particularly, the thing that I was working on look like a button, but it is really not a button. The label of this thing is actually the name of the user which vary for each user. If I declare the button with a fix width, depending on the label of the button, the button may not look good. I can use JavaScript to adjust the width of the button (based on the count of the characters in the label), but without using JavaScript, I can also make the width of the button adapt to its content using the above method. Perhaps, I can also achieve the same thing by trying different value for the display attribute. I can also achieve the same thing by using an inline element (either display:inline or display:inline-block) and set the width to auto. If we have an inline-block element, and we do not declare the width, I am not sure how the browser will behave. It may takes up the entire width of the screen, the remainder width of the screen, disappear, or collapse just enough to cover its content. I need to test this out some more.

How to style blockquotes?

<blockquote cite="http://news.ycombinator.com/item?id=1160248"><p>Some text.</p></blockquote>
<p class="cite"><a href="http://news.ycombinator.com/item?id=1160248">Author name</a></p>
blockquote {
  background-image: url(lquote.png);
  background-position: 0 2px;
  background-repeat: no-repeat;
  clear: both;
  text-indent: 23px;
blockquote > p {
  background-image: url(rquote.png);
  background-position: right bottom;
  background-repeat: no-repeat;
  display: inline;
blockquote {
    text-indent: -0.8em;
    font-size: 12px;

The negative indent will vary depending on the typeface, type size, and margins.

What is that CSS property that is similar to border but does not take up any space?

outline. Outlines are drawn on top of the element and therefore does not take up any space.

What are common errors in a CSS file?

  • The property and value are separated by a colon
  • Each property and value line are separated by a semi-colon
  • If the value is multiple words, put quotes around the value

How can I have background image that stretch the entire screen?

Create an image that is much wider than you need and set the background-position to "50% 50%". This will center your background image inside the element and as the element grow wider, more of your image gets revealed, while the entire image remains centered.

Why some fonts appear larger than other fonts even though we declare them with the same size?

Different fonts are designed differently. When fonts are created, they are set in a relation to what is called an em square or em box. Some fonts are small and all parts of their characters are contained within the em square. Other fonts may have their descenders or ascenders outside the em square.

When we declare a font size by any method (unit), we are setting the size of the em square. Because the relationship between the em square and every font is unique, there can be significant visual differences between various fonts set at the same size. The css property font-size is to provide a size for the em square, and not the size of actual characters.

Some fonts, especially those specifically designed for screen, may appear wider and / or taller than other fonts. This means that these fonts have a larger aspect ratio. If you use fonts with different aspect ratio, some people may see your pages with a much smaller font size than others.

What is the purpose of the word-spacing property?

The word-spacing property controls the amount of spaces between words. The default value of word-spacing is normal, which is also equivalent of the value 0. Negative values will bring the words closer together. Positive value will push them a part. A common misunderstanding is that the value of 0 will cause the words to have no spaces between them, and any negative value will make the words overlap.

What is the purpose of the letter-spacing property?

The letter-spacing property controls the amount of space between letters in your text. Some subtle but pleasant effects can be produced by separating letters slightly more than the default value of normal or 0:

p {
    letter-spacing: 0.05em;

Letters can also be pulled together by declaring a negative value for letter-spacing. This effect is sometimes used to squash text into a smaller area, but should not be used for big chunks of body text.

Shorthand for line-height:

The line-height value is written in conjunction with the font-size (the values are separated by a slash) using the font shorthand property:

font: 100% / 1.2 arial, helvetica, sans-serif;

Shorthand for font:

font: [style] [variant] [weight] size families

If optional attributes are omitted, they will not inherit from parent (line-height included). Optional attributes must come before mandatory attributes. We can combine size and line-height: 34px/100px. Families is a list of possible fonts separated by commas. If a font name contain white space, that font name must be quoted

Fonts properties include font-style, font-variant, font-weight, font-size, line-height, font-family.

font: font-style font-variant font-weight fond-size / line-height font-family
font:italic small-caps bold 1em/140% "Lucida Grande",sans-serif

font-style: italic
font-variant: small-caps
font-weight: bold | 400 | 700 | 100 | 200 | 300 | 500 | 600 | 800 | 900

When using font shorthand you can omit any values except font-size and font-family. You always need to give values for those, and in that order.

Shorthand for colors

#000 is the same as #000000
#369 is the same as #336699

Shorthand for Margin and Padding properties

margin: 1px        ; all 4 margins are the same
margin: 1px 2px      ; top and bottom margin both equal to 1, left and right margins are 2
margin: 1px 2px 3px    ; top margin is 1, right and left margins are 2, bottom margin is 3
margin: 1px 2px 3px 4px  ; top margin is 1, right margin is 2, bottom margin is 3, left margin is 4

The same TRouBLe rule applies to padding.

Shorthand for borders:

border:width style color;

The same syntax can be used with border-top, border-right, border-bottom, and border-left. You don't have to specify all three values. Any omitted values are set to default values. The default values are medium for width, none for style, and the value of the element's color for color. Note that the default value for style is none, so you do need to specify a style if you want the border to be visible.

The border-width, border-style, border-color properties use the TRouBLe rule mentioned above.

Shorthand for background properties:

Instead of using background-color, background-image, background-repeat, background-attachment, and background-position to specify an element's background, you can use just background:

background:#f00 url(background.gif) no-repeat fixed 0 0
background: color imageURL repeat attachment position

As with the border and border sides properties, you don't have to specify all values. If a value is omitted, its initial value is used. The initial values for individual background properties:

color: transparent
image: none
repeat: repeat
attachment: scroll
position: 0% 0%
  • background-color: sets the background color of an element. The color can be specified as a hex value, an rgb value, or by one of the limited color names. The background-color can also be set as transparent or it can be set to inherit the background-color of its parent element.
  • background-image: sets an image as the background of an element and it’s value will look like url(“path-to-an-image”). The background-image property can also have values of none and inherit
  • background-repeat: sets how a background-image is repeated. Values are repeat, no-repeat, repeat-x, repeat-y, and inherit
  • background-attachment: set how the background image will move with the page. It can scroll (moves with the element as the page scrolls), remain fixed (stays in position even when the page is scrolled), or inherit from the parent element
  • background-position: sets the starting position of the background image within the element. Images can be set to start vertically at the top, center, or bottom and horizontally at the left, center, or right. The background position can also be set to start a fixed amount or a % from the top left corner of the element.

background: aqua url(“clouds.png”) repeat-x fixed top;

You don’t need to specify all the properties when using the shortcut, but you do want to use the right order. Any property you don’t specify will be assigned a default value as follows:

  • background-color: transparent
  • background-image: none
  • background-repeat: repeat
  • background-attachment: scroll
  • background-position: 0% 0%

Shorthand for list properties:

List properties include list-style-type, list-style-position, list-style-image.

list-style:square inside url(image.gif);

Shorthand for outline properties:

Outline properties include outline-color, outline-style, outline-width. The outline property is rarely used due to lack of support by browsers. The shorthand:

outline:#f00 solid 2px;

Outlines have some interesting characteristics that make them useful. Unlike borders, outlines do not take up any space, and are always drawn on top of a box. This means that hiding or showing outlines doesn't cause reflow, and they don't influence the position or size of the element they are applied to or that of any other boxes. Outlines may also be non-rectangular.

Cross-browser transparency:

#your _div {
    -khtml-opacity: 0.5;
    opacity: 0.5;

Alternative way to create a horizontal rule without using the <hr> tag (which by default does not look nice):

<div class="hr"></div>

.hr {
    height: 1px;
    background-color: #BCBCBC; 
    line-height: 1px; 
    font-size: 0px;

The above code use a div with a class name "hr", and it does not use the <hr> element. Alternatively, you can add either border-top or border-bottom to one of the existing DIV elements.

How to let the first letter of the paragraph float to the left?

See http://www.w3schools.com/css/tryit.asp?filename=trycss_float4

How to let an image float to the right in a paragraph?

Just use:

img {
    float: right;

See http://www.w3schools.com/css/tryit.asp?filename=trycss_float

How to let an image with a caption float to the right?

See http://www.w3schools.com/css/tryit.asp?filename=trycss_float3

How to create a horizontal menu?

Just use:

ul {
    list-style-type: none;
li {
    display: inline;

See http://www.w3schools.com/css/tryit.asp?filename=trycss_float5

How to change the cursor?

.className { cursor: cursorType }

where cursorType:

  • auto: the default cursor
  • crosshair: gun-style cross
  • default: no change
  • pointer: the normal hand cursor when you mouseover a link
  • hand: a value only supported by MSIE, use pointer instead
  • wait: hour-glass
  • text: the vertical I-beam for selecting text
  • help: arrow with a question mark
  • move: crosshair with arrows on the ends
  • n-resize
  • ne-resize
  • nw-resize
  • e-resize
  • w-resize
  • s-resize
  • se-resize
  • sw-resize

How can we display fancy headings (gradient text / heading) without having to use Photoshop on each heading?

This is possible. To implement this, we need a PNG image, and an extra span tag:

<h1><span></span>Some text</h1>

The PNG image is overlay on top of the text. The key point here is: h1 { position: relative } and h1 span { position: absolute }:

h1 {
  font: bold 330%/100% "Lucida Grande";
  position: relative;
  color: #464646;
h1 span {
  background: url(gradient.png) repeat-x;
  position: absolute;
  display: block;
  width: 100%;
  height: 31px;

Since IE6 doesn’t render PNG-24 properly, we need to use Unit PNG Fix or:

<!--[if lt IE 7]>
    <style type="text/css">
        h1 span {
            background: none;
            filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='gradient.png', sizingMethod='scale');

For those semantic lovers, if you don’t want to have the empty <span> tag, you can use the following:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
        //prepend span tag to H1

jQuery code to insert the span tag into the DOM.

We still need to use a graphic editor to create a new PNG image every time we change the color of the text or the color of the background, but this is certainly a whole lot better than having to create each individual heading using a graphic editor. As long as we don't change the foreground or background color of the heading, we are good forever.

This trick is only suitable for solid background color elements. Your gradient color (PNG image) must be the same color as your background color.

If your gradient image is taller than the heading, the text will not be selectable.

By messing with the above CSS, and creating PNG images, we can create interesting effects. We can put the gradient at the top, bottom, left, right. We can give text a metallic look, vertical stripes, horizontal stripes. We can apply pattern over text.

What is a pseudo-class and what is a pseudo-element?

A pseudo-class is a particular state in which an actual HTML element can find itself. Think of it as a virtual class that is applied to the element automatically by the browser under certain conditions. A pseudo-element is a part of the document that CSS lets you style even though it isn’t an actual HTML element. It’s like a virtual HTML element—something you get to style even though it doesn’t have actual HTML tags around it. See http://www.sitepoint.com/3-things-almost-one-knows-css/


  1. :hover
  2. :checked
  3. :nth-child(even)
  4. :nth-child(2n)
  5. :nth-child(odd)
  6. :nth-child(2n+1)


  1. :first-line

In a flexible page layout, you can’t look at the HTML code of a page and say “that element there contains just the first line of the paragraph’s text”. The browser does the word-wrapping depending on the width of the paragraph, which is something you don’t get to control in a flexible page layout. :first-line is the pseudo-element that lets you apply styles to the first line of text in a block, no matter where that first line wraps to the second.

So I would say that a pseudo-class applies to the entire element, but a pseudo-element doesn't even exist or only apply to a particular part of an element.

In the CSS3 Selectors spec, in an attempt to distinguish the two, it changed the syntax so that pseudo-element selectors use two colons (::first-line), while pseudo-classes still use one (:hover). Of course, for backwards compatibility, browsers must support both versions.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License