Last Updated: 25 Jul 2023

   |   

Author: dordal

Basic CSS Reference

This is a quick 'cheat sheet' for CSS (Cascading Style Sheets).

Selectors

  • selector: The selector defines which piece of the document will be selected (e.g. to select all <p> tags with a class of foobar, you'd use p.foobar {})
  • declaration: a combination of properties and values that declare something about a selector (e.g. p.foobar { color: red; } ). The 'declaration block' is the set of all declarations for a given selector.
  • Basic selectors allow you to select all elements with a certain HTML tag (e.g. to get all <em> tags: em {}), all elements with a specific class (e.g. .myClass {}), or a single element tagged with an id attribute (e.g. #myElement {}). Of course, you can mix and match; em.myClass {} would only get <em> elements with myClass (e.g. <em class='myClass'>)
  • You can apply multiple class selectors in a single element selector. For example, .hello.there {} would match ONLY elements with class='there hello' (in any order). This also means that period isn't valid in a classname.
  • You can also create attribute selectors, e.g p[class] would select all <p> elements with a class attribute. This can be useful for selecting various types of input elements, e.g. input[type=“radio”] {} or input[type=“checkbox”] {}
  • You can create descendant selectors, these basically ask for a child element that is a descendant of another, e.g. h1 em {} would get all elements where an <em> tag is inside an <h1> tag. The <em> tag can be any number of levels down; if you want to select an <em> only if it is the immediate child of an <h1> tag, you'd use h1 > em {}.
  • There are pseudo classes you can use to select things based on actions that have been taken in the document. a:visited {} is one good example; it lets you select all visited links. You can also combine these with normal classes, e.g. a.foo:visited {}. Other pseudo classes include hover, active and link.

Sizing

  • CSS has many methods for sizing objects. em is the height of the current font (as defined by font-size), ex is the height of a lowercase x (although generally is just 1/2 the font size), px is pixels. There are also absolute measurements, such as in, cm, mm, pt (72/inch), etc.
  • It's generally best to use relative measurements… pixels when those are necessary (they scale to a 96dpi 'reference pixel' for printing) and ems for other measurements, esp. those that should grow or shrink. Percentages are also good, but fixed measurements such as points, centimeters or inches are not.
  • That's because monitors are all set to different dpi settings, and so using an absolute measurement will change the number of pixels in a given measurement. For example, if you say margin: 1in and the monitor is set to 120dpi, then you'll get a 120 pixel margin. But if your monitor is set to 96dpi, then you'll get a 96 pixel margin.

Text

  • The font-size declaration lets you control the size of fonts. It is generally best to do these in either pixels or percentages (e.g. font-size: 12px;). Don't forget that percentages inherit, though (e.g. 80% * 80% = 64%).
  • font-weight lets you control the boldness of a font. You can do this with numbers (100 to 900 in 100 increment values), but nobody does. Instead, use normal and bold or maybe bolder and lighter. For example: font-weight: bold;
  • font-style can be either italic or oblique (or normal), but italic is what you want. Your browser will pull an oblique face if it can't find an italic face, but not the other way around. font-variant can be used to do cool things, like small-caps. text-transform lets you force text to all caps, to lowercase, etc. text-decoration handles junk like strikethrough; the most common use of text-decoration is text-decoration: none on an <a> element, which removes the underline from a hyperlink.
  • There is an overall font declaration that lets you specify multiple properties at once. It can also take a few specific keywords: caption, icon, menu, message-box, small-caption, status-bar. These actually represent an entire set of font properties (font-family, font-style, color, font-weight, etc.) which make the font look like the system font in question. This can be useful if you're building web-apps or the like.
  • text-indent lets you both indent and outdent of the first line of text.
  • Horizontal and vertical alignment can be done with the text-align, line-height and vertical-align declarations. Note that line-height only specifies minimum values
  • letter-spacing and word-spacing adjust their namesakes. They can be handy from time to time.
  • white-space can be used to adjust the fact that browsers normally collapse multiple spaces into one. You can use 'pre' which is like HTML's <pre> tag, or 'nowrap', which doesn't wrap things. And there are a few others.

Opacity

  • You can set the transparency of an element with the opacity property

Block Elements & The Box Model

  • CSS layouts are fundamentally based on the CSS Box Model, which lets you create 'boxes' (of text, empty space, graphics, etc.) on the page, and then control how they are positioned and sized. Pretty much every element on a page is affected by the box model.
  • Any given box has a content area, padding (space inside the border), a border, and then margins (space outside the border). Width and height generally go from the inner edge of the box, not the outer edge. So if you make a box with width: 100px; padding: 10px;, the total width of the box on the page will be 120px (100px width + 10px left side padding + 10px right side padding).
  • Any given element in an HTML document can be either 'block level' or 'inline'. Block elements are generally used for layouts, and have a linebreak both before and after the element unless otherwise specified. Inline elements are…well… inline in the content, and do not have said linebreak.
  • display changes elements to block or inline. Therefore, if you wanted to change a <div> element to be inline, you'd say <div style=“display:inline;”></div> Note if you change an element, you change its display property only, and not the nature of the element. This means (for example) that it doesn't become syntactically valid to wrap an <div> tag in an <a> tag, even if you made the <div> an inline element.
  • display:none; completely removes the element from the flow of the document. This feature is used all the time in modern Web 2.0 apps to hide controls, popup boxes and other elements that should only appear once the user has interacted with the page in some way.
  • visibility: hidden; has a similar effect to display: none, but is a little different in that it just hides the element, leaving blank space for it in the document rather than completely removing it.
  • Any given element is either a non-replace element or a replaced element. Non-replaced elements are like the <p></p> tag; text goes inside the tag. Replaced elements are like the <img> tag; the tag is only a placeholder for something else that goes there.
  • As noted, all elements have margins and passing. However, margins/padding seems to behave a bit 'funny' for inline elements. See Inline Elements for more.
  • Horizontal margins can be set to auto (which centers an element if you do it for both sides), but padding MUST be specified or it defaults to zero. auto can also be used inside an element (e.g. width: auto). Setting horizontal margins to auto is a better way than text-align to center an element.
  • Vertical positioning is similar to horizontal positioning… margins can be set to auto, height can be auto, and padding can't. But there is a difference: auto margins center horizontally, but they get set to zero vertically.
  • Margins can also be negative, which makes the containing box bigger than the outside box. This can be useful in a few specific cases.
  • Margins/padding can also use percentages instead of absolute pixels. This can be good for scalable layouts, as you can do something like padding-left: 5%; width: auto; padding-right: 5%
  • height defines the height of an element. If there is more stuff than can fit in the element, you can use the overflow property to hide it, let it overflow, or add scrollbars. If height is defined as a percentage, the immediate parent element must have its height set, or else height defaults to auto. Rather annoying.
    • This means in order to make a full page layout, you have to set the height of both the html and body elements
  • Collapsing margins: vertical margins can collapse, which means that two vertical margins overlap so only the bigger 'applies'. This is unique to vertical margins, and doesn't affect vertical padding, horizontal margins, etc.
  • Lists (<ol>, <li>, <ul>) are just strange. There are some non-standard ways to control list markers etc., but these are still in flux. See Lists for details
  • All elements can have borders. Borders are pretty much like you'd think they'd be… you can give them a border-width, a border-style, and a border-color. There is also a combined property: border: 1px solid #000000;
  • Borders can be set to transparent: border-color: transparent This is cool if you need to replace the border when you're hovering over an item, and therefore don't want to set it to 0px when you're not (because the size would change).
  • Borders can have styles; there are a bunch but the only cool ones are solid, dotted and dashed.
  • You can give any element a min-width and min-height, as well as a max-width and max-height. IE6 doesn't honor these parameters, however.

Inline Elements

  • Inline elements can be replaced or non-replaced, just like block elements. <span> is sort of the inline equivalent to the block element <div>
  • All inline elements implicitly go in an 'inline box', which is basically as wide as the content, and as high as the content + leading. (Leading can, and usually does, happen if you have a line-height > font-size). In most cases, the content area (which is what has the text itself in it) will be smaller than the inline box. However, you can force it the other way, e.g. font-size: 24px; line-height: 12px. Then the content area will spill out of the inline box, and the text may overlap other lines.
  • line-height is what controls the height of the lines. Basically, it's rather funky, but best practice seems to be to use either a scaling factor (line-hieght: 1.2) or base it on ems.
  • You can adjust the height of one element relative to another with vertical-align. This can get a bit complicated, though, and the most flexible value (percentages) don't seem to work right in IE (even IE7). Valid values (that do work) are top, bottom, text-top, text-bottom, middle, super, & sub. Note that vertical-align ONLY works on inline elements, not block level elements.
  • On inline non-replaced elements, padding and borders DO NOT alter the height or width of the content area, and thus the line-height. Therefore, you get all kinds of weird affects if you apply padding or borders to inline elements, with borders overlapping other lines, etc. Margins do not affect the top and bottom aspects of the content-area, but do affect the left and right aspects. So you can say margin-right: 20px; to indent some text, but you can't say margin-top: 20px to push it down.
  • However, even though padding doesn't alter the height of a line, it does get applied to inline non-replaced elements, which means you can make a background extend above or below a line using padding.
  • The ONLY things that affect line hieght are line-height, font-size, and vertical-align.
  • On inline replaced elements (img, etc.) padding, borders and margins work more or less like box elements.

Hybrid Elements

  • There are no hybrid elements, but there are a few hybrid display properties (in addition to the standard display: inline and display: block). See QuirksMode for more.

Background Images

  • Background images can be applies to just about any element, including stuff like <input> and <select>
  • You probably want to specify a background-color in addition to the background image, in case the image doesn't load.
  • Background images are not inherited, at least not unless you manually specify inheritance. This is what you want, because otherwise each element in the page would re-tile the background, which would look like crap.
  • You can use background-repeat to control whether a background image repeats. Valid values include repeat, no-repeat, repeat-x and repeat-y. Amazingly, all of these are actually useful for various purposes. Repeat repeats from the center of the image, which is usually the top left corner, unless you've moved it with something like background-position: 50% 50%;
  • background-position lets you position the image, which is useful for background images for pages, etc. The image goes from the inner border… pretty much what you'd expect. Anything inside the border is filled with image; anything outside is not filled (e.g. margins are not filled with the image)
    • background position can either be words, percentages or pixels.
    • background-position: right bottom puts the image in the lower right corner
    • background-position: 50% 50% puts the middle of the image in the middle of the element (e.g. the middle of the div)
    • background-position: 10px 10px positions the top-left corner of the image over 10px and down 10px. You can also use negative numbers to position it so that only an interior part of the image is showing (see Using One Image for Multiple Buttons (Sprites) for a practical application of this).
  • background-attachment: fixed lets you fix an image to the viewport, not the element it is 'attached' to (so background-position: 10px 10px would put it 10px down and right from the top of the viewport, not the element). If you scroll, the image doesn't scroll with the document, even though the element it is attached to does scroll. However, you can only actually see the image when it is inside of the element, which means that you probably will only see your image part of the time (unless it is huge). If you want to show a non-scrolling background image for the entire page, you could use background-attachment: fixed and attach it to the <body> tag.
  • There is, of course, a background: property that lets you apply everything at once: background: url(foo.gif) white no-repeat scroll top left; You can omit any properties that you don't want; as with other shorthand notation they'll get set to defaults.
  • One good, modern way to put images in your page is to use background images on a <div>. You create one big image, with all the components of all your images in them (e.g. all the buttons from your navigation bar in one image). Then you create <div>s that are the appropriate size (using width and height) for each button. See Using One Image for Multiple Buttons (Sprites) for details.
  • You can also use 'image replacement' techniques to replace text with an image. This is good if you want to have image-based navigation, but still want text for visually-impaired readers and for the search engines. See CSS Image Replacement for details.

Layout - Floating

  • CSS Box Model's ability to float elements is at the core of its layout control.
  • The float: property is used to control 'floating', which lets content in the 'normal flow' flow past the floated element. You can float: left, float: right, float: inherit or float: none. If you are floating a non-replaced element (e.g. a <p> tag) you must manually declare a width, or the width of the non-replaced element will tend toward zero. The width can either be specific (e.g. 400px) or dynamic (e.g. 50% of the containing block). Don't forget that width specifies the width of the content area; if your floated div has padding or margins these will be in addition to the width.
  • Every floated element has a 'containing block', which is basically the immediate block level parent. Through a complex series of rules, a floated element has to 'fit inside' the top, left and right of its block level parent (and specifically, inside the inner box of the block level parent (e.g. inside all borders, margins and padding)). A floated element does NOT have to fit inside the bottom of the containing block, which means will can 'float out' of the containing block if it is taller than the containing block.
  • If you want to force a floated div inside the containing block, you must put a empty clearing div at the bottom of the containing box:
    <div id="container">
    <div id="floater" style="float:left; width 100px;">
    floating text
    </div>
    <div id="cleardiv" style="clear:both;"></div>
    </div>
  • Floated elements can't overlap.
  • There are a bunch of other rules, but they are confusing to understand and (apparently) not consistently implemented in all browsers.
  • If you don't want an element in the normal flow to flow past a floated element, you can add a clear: property to it, e.g. clear: right, clear: left or clear: both. This basically says to 'push down' the element the clear is attached to so that no elements float on its left side, right side, or both sides.

Layout - Positioning

  • Positioning lets you actually place an element in a certain spot on a page or within a containing box. There are four types:
    • static: normal position (every element has this by default)
    • relative: the positioned element's box is offset by some distance from its original spot (not from the edges of the containing box). The space the element would have occupied (had it not been positioned) is left empty.
    • absolute: it is positioned within the containing block, but outside of the flow of the document, so other elements fill in the space it would have occupied. The positioning is relative to the containing block; e.g. if you say right: 20px then it will be 20px from the right edge of the containing block
    • fixed: like absolute, but relative to the viewport. Not supported in IE6 and before. IE7+ is OK.
  • when you actually position something, it doesn't do you a whole lot of good to just say it has unique positioning (it won't go anywhere). You need to offset it to make it actually move. This is accomplished with top, right, bottom, left. e.g. top: 20px;
  • In order to make positioning work, you need to put the element you want to position inside a 'containing box' (for example, a parent <div>), and then give that containing box a non-static positioning. For example, your containing box might be a <div> with position: relative, and the <div> you actually want to position is position: absolute; top: 20px;
  • Position values can take percentages, just like margins, padding, etc. So if you say: top: 50%; bottom: 0; left: 50%; right: 0; it will position the element in question in the bottom right corner of the containing box. (You may also have to manually set width and height of the element to be 50%, depending on the size of said element)
  • If you need to set the width or height of a positioned element, you can do so with the standard width, height, min-width, min-height, max-width, max-height parameters
  • z-index lets you set which elements overlay other elements. You give it a number, either positive or negative. The larger the number, the 'closer to the viewer' it will be. There is no practical limit (that I'm aware of) for the numbers that you can assign to z-index. It only affects positioned elements; you can't seem to z-index elements that are the standard position static. Note that means that ALL elements have to be positioned, e.g. if you want to overlap one element with another, BOTH elements have to have position: relative (or absolute)
  • Each z-index is local to its group of elements. For example, consider three overlapping divs, with the third div inside the first div. If you declare the first div with z-index: 50, the second with z-index: 70, and the third (inside the first) with z-index: 30, you might expect the third div to be on top (50+30=80, > 70). But it isn't… that's because its only +30 within the context of the second div, not within the context of the document.

Tables

  • Tables have special layout properties in CSS
  • First up, you don't have to use the standard <table>, <tr>, <td> tags if you don't want to. You can create tables out of <div>s, and then apply table display properties such as display:table, display:table-row, display:table-cell, etc. (Although why you'd want to do this I don't know, since the <table> commands are syntactically valid markup). Also, IE (including IE7) doesn't support this.
  • There are also display properties for all the weird table tags that you never use, like colgroup.
  • Notably, tables declared with divs and display properties don't seem to have any border-spacing by default. Tables declared with <table> still do. You can set this to zero with border-spacing: 0px;, but it doesn't work in IE until IE8. Therefore, the nasty hack workaround is to put cellspacing=0 in the table tag itself. vacskamati also has a fix that is CSS only, and seems to work well in my testing.
  • Borders can collapse into each other (overlap) with border-collapse: collapse. This is somewhat akin to the way vertical margins can collapse. Otherwise, each cell can have its own borders with border-collapse: separate. Generally, you'll probably want to leave this at separate (the default).
  • Table cells have borders and padding, but no margins.
  • empty-cells (not supported by IE) lets you hide or show empty cells.
  • Setting table (and table cell) width and height can be an exercise in frustration.
    • Table width can be calculated in one of two ways; either table-layout: auto, which looks at the size of the text and sort of auto-calculates what it thinks width should be, or table-layout: fixed, which looks only at manually assigned cell widths, etc. and forces the content to fit into whatever width it comes up with. In order for fixed to work, it seems that you have to give the overall table a fixed size… if 'auto' is specified for the table width (either explicitly or implicitly) it will default to table-layout: auto;
    • If you're using table-layout: fixed;, width values that you assign to cells generally seem to work.
    • If you're using table-layout: auto; the browser calculates min and max width's for each cell, depending on the width: you give it as well as the size of the content in the cell and a number of other factors, and then sort of auto-figures-out what it thinks you want. That's why widths never seem to come out correctly.
    • height is apparently supposed to be a minimum height; if the browser thinks that the height of a table needs to be bigger for some reason, it can make it bigger. CSS 2.1 is apparently pretty vague in this area.
  • Alignment within cells is done via text-align (right, left, center) and vertical-align (top, middle, bottom, baseline), and actually works pretty well, although FF seems to not do baseline properly.

Lists

  • CSS has some support for modifying the styles of lists, such as those defined with <ul> and <li>
  • list-style-type can be set to any number of things: square, circle, decimal, upper-alpha, etc.
  • list-style-image lets you set an image for the list item. You may want to set a backup list-style-type in case the image can't be found.
  • list-style-position lets you set whether the bullet is 'inside' or 'outside' the list. In practice, this basically means whether bullet elements sit inside or outside the border of the list (if you set the border property)

Cursor

  • You can change the cursor with the cursor: declaration. e.g. cursor:pointer, cursor:crosshair, cursor: help, etc. There are too many values to cover; details are in the Mozilla Developer Center.
  • You can also make your cursor into a custom graphic. If you do cursor: url('mypointer.cur'), pointer, then the browser will try to load the file 'mypointer.cur' for the cursor, and flip back to the default if it can't read the file or doesn't support the .cur file format. If you want, you can specify multiple files and it will try each one: cursor: url('mypointer.cur'), url('mypointer.gif'), url('mypointer.png'), pointer

Outlines

  • outline lets you put an outline just outside the border of an object. These are kind of like borders, and share the same styling properties (e.g. outline: 1px solid black;). Unlike border, however, they do not affect the flow of the document, and they must be uniform (e.g. there is no outline-top, outline-right, etc.).
  • Outlines are generally used to highlight something the user needs to do or is doing. For example, your validation code might make a red outline around any form inputs that aren't filled in correctly.

Media Style Sheets / Printing

  • CSS supports creating different style sheets for different types of media. For example, one may be for the screen, and one for print. You'd use the same markup, but the screen one would have more graphics, etc. than the print one.
  • You select what the style sheet should be for when you include it, using the 'media' attribute:
    <link rel="stylesheet" href="styles-print.css" media="print">

    There are a bunch of mediums other than 'print', and 'screen', but they are mostly fairly useless.

  • When creating a print stylesheet, there are some things you want to think about:
    • Probably force black text on a white background
    • Consider using points (which printers know how to deal with) and serif fonts such as Times New Roman, which are easier to read
    • If you've got more than one column, lay it out into one for the printed page
  • There are a number of print specific implementation rules in CSS2.1, but support seems to be pretty poor. page:, size:, etc.
  • But the coolest thing is putting in page-break-before: always and page-break-after: always, which lets you specify where a document should be broken up. If you have (for example) sections in your document, you may want to put a page-break-before: always on each section header, so that each section starts a new page when the document is printed.
  • You can also do your best to keep an element (such as a div or table) on one page by saying: page-break-inside: avoid; This isn't guaranteed to work, but the user-agent will try.

Styles with Javascript

  • Most properties of an element in CSS can be set with javascript. But anything dealing with styles needs to be set via the style property. e.g. myDiv.height doesn't work; you need myDiv.style.hieght = '400px'

Discussion

Enter your comment. Wiki syntax is allowed: