CSS Tips

Positioning

Don’t use display:block on inline elements to nest block level elements(p,div,h1,etc) inside them

Don’t use relative positioning to move a nav menu or list of block-level hyperlinks to make sure that the hover area stays within the defined width and height of the anchor tags. This is especially important for anchor tags within lists

Absolutely positioned elements will shrink-wrap to fit their contents unless you specify their dimensions. You can specify the width by setting the left and right properties, or by setting the width property. You can specify the height by setting the top and bottom properties, or by setting the height property

Set position:relative on the containing block of an absolutely positioned element, even if you are not actually shifting the position of the box. This allows you to control the boundaries of the absolutely positioned element instead of basing your calculations off of the dimensions of the entire HTML page.

For a relatively positioned element, the top, right, bottom and left properties specify the relative distance to shift the content of the element. These values complement one another in relative positioning, top:1em equals bottom:-1em, so there’s no need specify both top and bottom (or left and right) for the same element, because one of the values will be ignored.

For an absolutely positioned element, the top, right, bottom and left properties specify the distances from the element’s edges to edges of its containing block. All four properties can be used at the same time(except in IE6), to specify the distance from each edge of the element to the corresponding edge of the container. You can also specify the position of one of the corners of the absolutely positioned box—say by using top and left—and then specify the dimensions of the box using width and height (or just use no width and height if you want to let it shrink-wrap to fit its contents).

Any container defined as an absolute- or fixed-position element becomes, for all practical purposes, a block-level element.

If you use a relatively positioned element as a container for an absolutely position element, the absolutely positioned content can maintain its position relative to it, regardless of the flow of the inline content.

If absolutely positioned elements overlap, use z-index to give priority of one over the other

Use even numbers to avoid covering 99% of the page

Use margin:0 auto and width:996px to center all container divs

Avoid using absolute or relative positioning on main content divs so page scrolling will not be inadvertently broken

Use a fixed width for all relatively positioned text to make sure it does not overflow its parent div or become truncated

Use block level tags around all inline elements so that no inline elements are a direct child of the container divs. Remember to set the dimensions of the inner blocks to be less than the dimensions of the container divs.

Use position:relative and left:xxx(where xxx is equal to the remaining space between the start of column and the edge of the window) to remove the space between the rightmost column of the layout and the body.

Use margin-left:xxx(where xxx is the same as above) as well as margin-right:yyy(where yyy is the minimum value needed to make the column visible) to achieve the same effect

Use position:relative when attempting to move elements within a container without moving any neighboring elements instead of using margin and padding adjustments

Use visibility:hidden instead of display:none to create a placeholder for unseen elements

Use display:block or vertical-align: bottom on images inside tables to avoid extra whitespace

Use display:table or display:inline-block instead of floats to align block level elements horizontally

Use display:block and set both width and padding values to align inline elements vertically and to align wrapping text and links

Use margin: 0 auto on elements with a defined width to horizontally center block level containers

Use margin-left:auto; margin-right:auto; instead of margin:0 auto; on elements with a defined width in HTML emails to horizontally center block level containers

Use margin: 0 auto; display: table; to horizontally center content that has an undefined width in standards compliant browsers

Use text-align: center; for the container and text-align: left, display:inline-block, and display:inline (in a separate declaration to trigger hasLayout) on the block element to horizontally center content that has an undefined width in IE6 and IE7.

Use text-align:center for the container, display:inline-block(-moz-inline-box for Firefox 2) for the wrapper div, and display:inline for the content div to horizontally center content that has an undefined width across browsers. Set the wrapper div to display:inline in a subsequent IE specific declaration to trigger hasLayout. Set the content div to display:-moz-inline-box in a subsequent declaration to trigger the Firefox 2 experimental layout. In case the centered content wraps, use width:99% for the wrapper div to avoid issues in Firefox 3+ and Webkit browsers (Safari, Iron, Chromium, Chrome, etc). Add a fixed width div nested in the wrapper to address this in Firefox 2. The final cross-browser CSS follows this pattern:

.container { text-align:center; }

/* Use width of less than 100% to avoid Firefox 3+ and Webkit wrapping issues */
.wrapper { width: 99%; }

/* Use inline-block for wrapper and placeholder */
.wrapper { display:-moz-inline-box; display: inline-block; }

.ie67 .wrapper, .content { display:inline; }

.content { display:-moz-inline-box; }
<!--[if lte IE 7]>
  <body class="ie67">
<![endif]-->

<![if (!IE) | (gt IE 7 )]>
  <body>
<![endif]>

<div class="container">
    <div class="content">
        <div class="wrapper">
            <div>fff</div>
            <div>ggg</div>
        </div>
    </div>
</div>

Use display: table; height: 100%; for the container and display: table-cell; vertical-align: middle; for the content to vertically center content that has an undefined height in standards compliant browsers. Use height:100%; for the html and body tags as well if the container is the first child of the body.

Use position: relative; top: 50%; for the container and position: absolute; top: -50% for the content to vertically center content that has an undefined height in IE6 and IE7

Use height:100% for the html tag, body tag, container and an empty placeholder element plus display:inline-block; (-moz-inline-box for Firefox 2) and vertical-align: middle for the content and placeholder to vertically center content that has an undefined height across browsers. If an empty inline-block element (for example a span) is added inside the container and it is assigned height: 100%; vertical-align: middle then it allows to precisely get what we want: a line box with the desired height. The placeholder element is given 100% height to prop up the line box, so that vertical-align: middle has the desired effect. This will avoid the need for the aforementioned IE specific relative positioning workaround due to the lack of cross-browser support for display:table compared to display:inline-block. If the content is a block element, add display:inline in a separate declaration for IE6 and IE7 to trigger the hasLayout behavior. The final cross-browser CSS follows this pattern:

html, body, #container, #placeholder { height: 100%; }

#content, #placeholder {
display:inline-block;
vertical-align: middle;
}

*#content{display:inline;}
<div id="container">
    <div id="content">
        Vertically centered
    </div>
    <span id="placeholder"></span>
</div>

Use the aforementioned vertical centering pattering with display:inline for the content div and display:inline-block to an extra nested wrapper div to vertically center an image gallery in Firefox, Safari, and Chrome(no change needed in IE or Opera). Make sure the width of the wrapper is less than 100% to avoid the inline-block bugs in those browsers as well. Here is the cross-browser pattern:

html, body, .container, .placeholder { height: 100%; }

img { width:16px; height:16px; margin-left: 20px; margin-top: 10px; }

/* Use width of less than 100% for Firefox and Webkit */
.wrapper { width: 99%; }

.placeholder, .wrapper, .content { vertical-align: middle; }

/* Use inline-block for wrapper and placeholder */
.placeholder, .wrapper { display: inline-block; }

.ie67 .wrapper, .content { display:inline; }
<!--[if lte IE 7]>
  <body class="ie67">
<![endif]-->

<![if (!IE) | (gt IE 7 )]>
  <body>
<![endif]>

<div class="container">
    <div class="content">
        <div class="wrapper">
            <img src="http://microsoft.com/favicon.ico">
            <img src="http://mozilla.com/favicon.ico">
            <img src="http://webkit.org/favicon.ico">
            <img src="http://userbase.kde.org/favicon.ico">
            <img src="http://www.srware.net/favicon.ico">
            <img src="http://build.chromium.org/favicon.ico">
            <img src="http://www.apple.com/favicon.ico">
            <img src="http://opera.com/favicon.ico">
            ...
            ...
       </div>
   </div>
   <span class="placeholder"></span>
</div>

Specify the line height to be the same as the height of the containing element to vertically center inline text

Use margin-top: xxx (where xxx is equal to the height of the container div minus the height of the centered element). Divide this value by two to vertically center a block element

Use margin-left: xxx (where xxx is equal to the width of the container div minus the width of the centered element). Divide this value by two to horizontally center a block element

Use top: 50% and margin-top: -xxx(where -xxx is equal to half of the defined height in pixels) to center absolutely positioned content vertically

Use left: 50% and margin-left: -xxx(where -xxx is equal to half of the defined width in pixels) to center absolutely positioned content horizontally.

You may have to adjust the calculated margin-left values by about 10 pixels in IE specific style rules or conditional comments to account for box model differences.

Use position: relative; text-align:right; for the container, position: absolute; left:0 for the left aligned element, and display: inline or inline-block for the right element to emulate floating and create bookends for a masthead without encountering the side effects of floats

Use overflow:visible on any container that uses height to emulate min-height in IE6 to avoid inadvertently removing scrollbars

Use position:absolute or position:relative with margin adjustments instead of static positioning padding adjustments for better cross browser consistency when laying out content

Use absolute positioning to show important content(Headers, Breaking News) before the rest of the relative content loads

Create space on the page for absolute content by inserting placeholder divs which are equal to the dimensions of the absolute content or by applying margins for the static content which is greater than the width or height of the absolute content. Placeholder divs have the advantage of allowing another background color to be added that encompasses the entire area around the absolute content, which is especially useful in styling a header or footer

Use absolute positioning with margin shifting to reposition a class of elements (menu titles, footer text, gallery links) at once without giving them the same coordinates

Use display:inline when absolutely positioning headers and other block elements to remove hasLayout and avoid inconsistent display between IE and other browsers

Use vertical-align to center images and text on the same line. Don’t use the sub, super, text-top, or text-bottom values for cross browser consistency

Use vertical-align: middle to realign radio buttons and checkboxes with inline text

Use list-style-type:none for a <ul> element, display:inline for its <li> elements, and add right side margin for the <a> or <span> tags within to create a horizontal list that can used for tabs, menus, thumbnails, screenshots, etc.

Use display:table for the container div, display:table-row for the parent div, and display:table-cell for the nested divs to create rows and columns in standards compliant browsers. Use the display:table-cell divs as a container to divide a large row into multiple div blocks for any column

Use display:-moz-inline-box; (for Firefox 2) and display:inline-block; for other standards compliant browsers to create rows and columns without floats or display:table. Remember to declare -moz-inline-box; before display:inline-block; to ensure Firefox 3+ uses the latter.

Use display:inline and zoom:1 to create rows and column layouts in IE6 and IE7 since display:table is not supported. Add display:inline in a wrapper class (.ie .side, .ie .main{display: inline;}) or conditional comments to achieve the same effect as the zoom:1 trick without using the IE specific property. Use zoom:1 and height:0 for IE5.

Use matching elements when styling column layouts using inline-block, since mixing adjacent divs with paragraph tags may not work even if they have the same display properties

Use vertical-align:top with display:-moz-inline-box to display content the same way as display:inline-block on other browsers

Use -moz-box-orient:vertical; with display: -moz-inline-box; for Firefox 2 to vertically align multiple block level child elements in the inline box, and make sure a fixed-width block-level element contains any inline content

Use display:block to wrap inline content within -moz-inline-box blocks in order to render layouts in Firefox 2 consistently with inline-block on other browsers.

Use overflow:hidden and a fixed width for blocks within -moz-inline-box to prevent mysterious line wrapping and margin collapsing

If adjacent content overlaps -moz-inline-box blocks, make sure it is inside a block container

If you nest -moz-inline-box columns within a -moz-inline-box container, make sure width is auto for all the -moz-inline-box containers

If you use overflow:hidden along with -moz-inline-box, set a fixed width for the container

Use display: -moz-inline-block; and display: inline-block to create a thumbnail gallery using list elements that wrap and align consistently without floats

Use display:inline for an element with no children, such as a button or form field, that comes before an inline-block element. If the element comes after the inline-block element, it needs to be inline-block as well.

Use display:run-in for a inline-block element that comes before a block element, such as a form that has a paragraph next to it

Set text display properties (text-align, text-indent) on block elements to apply them on the inline or table-cell content they contain

Nest an absolute-positioned element within a relative-positioned container with set width and height to freely position a block within a certain area

Use table{caption-side:bottom;} to move a table caption below the table instead of the default position above the table

Use a defined height and overflow:auto on the tbody element to allow it to scroll independently of the table header and footer in Firefox

Use relatively positioning for elements inside a container with overflow set to auto or scroll on the container to allow them to scroll independently in IE6 and IE7

Use absolute positioning with percentages for the simplest, most consistent display of troublesome elements

Use position:relative on any elements which need to have a z-index value

Use position:relative; and top:xxx where xxx is equal to the line height of the grid to create a paragraph break for a span of text without a paragraph tag. This is useful to insert space between text which wraps a floated image without using a pre tag or a white-space: pre rule

An absolutely positioned element with an undefined width will shrinkwrap to the width of its parent

The top margin of a static block is ignored in IE when it immediately follows an absolutely positioned element, so it’s best to place the markup for those elements at the bottom of the HTML source

Only absolutely or relatively positioned elements can be animated using JavaScript

Use table-layout:fixed for data tables to make them use the declared widths of columns rather than shrinkwrap the content, which will also make them render consistently across browsers

Use display:block and set other styles for undefined HTML5 header, footer, nav, article, dialog, sidebar, etc. tags

Floats

IE6 and IE7 will place a floated element below an inline box that is its previous sibling

IE6 and IE7 will place an inline element below a floated element that is its previous sibling if it is floated to the right of that element

IE6 and IE7 will shrinkwrap an element styled float:left to the width of its containing block if the container has a right-floated child and an undefined width

IE6 and IE7 cleared elements will clear other nested floats even if they don’t share a containing block

IE6 and IE7 cleared elements will have twice their declared top padding when displayed

A floated box can overlap block-level boxes adjacent to it in the normal flow, so use the clear property to reposition static boxes in the flow

The clear property can be used on a floated element to force it below adjacent floats, which is useful for aligning multiple blocks floating in the same direction

The clear property specifies if an element can have elements floated to its left, to its right, or not at all. When an element does not allow floating on a side, the element appears below the floated element.

Internet Explorer versions up to and including 6 add three pixels of padding (in the floated direction) to adjacent line boxes.

In Internet Explorer versions up to and including 6, the left or right margins are doubled on floated elements that touch their parents’ side edges. The margin value is doubled on the side that touches the parent. A simple fix for this problem is to set display to inline for the floated element.

Internet Explorer for Windows versions up to and including 7:
will place a floated box below an immediately preceding line box
will expand a left-floated box to the width of the containing block if it has a right-floated child and a computed width of auto
will apply a layout to a floated element
don’t support the value inherit for any properties except visibility and direction

In Firefox versions up to and including 2.0, a floated box appears below an immediately preceding line box. A left-floated box with a right-floated child and a computed width of auto expands to the width of the containing block.

In Opera up to and including version 9.2, if the computed width of the floated box is auto and it has floated children, its width is computed as if the floats don’t wrap and aren’t cleared.

Use overflow: auto; display: block; float: left; margin: 0 auto; to position block elements onto the same line.

Floated elements are shrinkwrapped by surrounding block content unless overflow is set to auto or hidden on the surrounding blocks, in which case they are treated as inline blocks.

Floated elements following an absolutely positioned element will cause it to disappear in IE6 and IE7 unless the absolutely positioned element is set to clear:both

Instead of applying top margins to cleared static content apply bottom margins to floats for cross-browser consistency.

Floated elements do not support margin collapsing

Z-Index

Every element whose z-index is specified as an integer or whose opacity is not equal to 100% establishes a new stacking context in which the element itself is the zero z-index for its child elements, and its children are positioned relative to each other but cannot overlap elements outside of the container.

If a relatively positioned element is display:inline, its left/right and top/bottom offsets are based on its container only instead of the stacking context

A z-index of auto means that the element does not create a z-index of zero for its children, so their z-index value is relative to the other elements on the page.

In IE7 and under, relatively and absolutely positioned elements have an automatic z-index of zero. In addition, IE evaluates a z-index of auto as a z-index of zero. Therefore, two absolutely positioned elements inside different containers cannot overlap. If one of the parent elements has a z-index of 1, then it’s child can overlap the child of the other container. For dropdowns, raise the z-index of the currently hovered item instead of relying on the z-index of the menu itself.

Setting descending z-index values on the each relatively positioned div container so that the first div in the markup has the highest value allows absolutely positioned content inside of the first div to overlap content in all subsequent divs.

Any relatively positioned element with haslayout establishes a stacking context. If two elements are both relatively positioned, and one is set to z-index:1, it will be hidden under the second div if they overlap in IE.

To get a modal dialog box to overlap a select element in IE, use a positive z-index value and overflow:hidden; for the absolutely positioned div. Then insert an empty iframe inside conditional comments as a child element of the absolutely positioned div and style it position:absolute; top:0; left:0; z-index:-1; filter:mask(); and a defined width and height. This works because a select element behind an iframe will not be drawn by IE, even if it is invisible.

If two or more sibling elements have the same stacking level within their parent, they are rendered back to front in the order of their appearance in the HTML markup.

If you want relatively positioned elements in one div to overlap relatively positioned elements in another div, you have to raise the z-index of the entire div, or combine the content into the one container div

If you want one element to paint on top of everything else, but you want a child of that element to be behind everything else, make that element the only relatively positioned element, then position the child with a negative z-index

If you want one border color to overlap another on adjacent table cells, give that cell a higher z-index than the other. Use a border width of zero with the higher z-index to erase the border completely.

Typography

Never define font-size for an element without defining it’s line-height

Never define font-family lists using carriage returns since it won’t work in IE

Always reset the :visited color when you reset the :link/default color of a link for consistent behavior between IE and standards-compliant browsers

(font-size + vertical padding + vertical margin)/line-height for each element must be a multiple of a baseline number

(font-size + vertical padding + vertical margin) * line-height gives you the total height of each row of text

The difference between the line-height and font-size is called leading.

The top and bottom margins between the font-size and the line box are half-leading, so a 12px font-size on a 18px line will half 3 pixels of space on the top and bottom between the text and the next line

The leading for inline replaced elements(img, object, select, etc) in IE6 collapses the half-leading of the line with the half-leading of the preceding and following line. To workaround this, give the replaced element top and bottom margins equal to half of the difference between its height and the line-height

Set vertical margins equal to the global line-height to maintain vertical alignment for text with standard size fonts. For text equal to the line height, set vertical margins and line-height equal to 100% of the text height

Use percentages for all fonts to allow for browser selectable sizing

Use three char styles for colors (#FC0 = #FFCC00)

Use the widows and orphans properties to set the minimum lines of text displayed at the top and bottom of the page respectively when generating page breaks in CSS

Never set percentages directly on a tag, always reference an ID or class to avoid cascading issues

Use margins and the <wbr> tag (or its equivalents) to control wrapping and vertical alignment of list items and headers with long unbroken strings when overflow:hidden is not an option

Use a:first-line to set a specific line-height for links that wrap

Use text-decoration:none and list-style-type:none to remove bullets and underlines from links and lists respectively.

Use direction: rtl; on the ul or ol to right align bullet points next to a list item. If there are spacing issues, use a bullet background-image with background-position:right center as an alternative

Use text-decoration:line-through instead of the deprecated <s> and <strike> tags to strikethrough text

Use text-transform:capitalize to capitalize headers and section titles

Use p:first-letter to set a large font and create a literature style drop cap effect for paragraphs

There can be only one pseudo-element per selector, so :first-letter and :first-line cannot be used together

In IE6 and IE7, a pseudo-element has to be followed by whitespace to be parsed correctly, so format your style sheet accordingly to avoid mysterious errors like this:

P:first-letter{ color: blue; } /* Fails due to the lack of whitespace */

Succeed - P:first-letter { color: blue; } /* Note the added space */

In IE6 and IE7, a pseudo-element has to be at the end of a selector to be parsed correctly, so make sure to put :first-line or :first-letter after any :hover, :focus, or :first-child pseudo-classes as follows:

P:first-letter:hover { color: blue; } /* Fails due to the lack of whitespace

P:hover:first-letter { color: blue; } /* Note the ordering */

Use display:list-item and list-style-type:decimal to enumerate an element that is not semantically part of a list

Use list-style-type:decimal to enumerate an unordered list when you cannot modify the markup

Use a margin reset on ordered list with hasLayout and add margins to the list items to prevent the
enumeration from being cropped

Use white-space:pre with a return after each letter to display text that reads vertically

Use white-space: -moz-pre-wrap; for Firefox 2, word-wrap: break-word; and white-space:pre; for IE6/7, the pre tag for Safari 2 and white-space: pre-wrap for Opera, Safari 3, and Firefox 3 and to force wrapping on predefined text

Use white-space: pre; on a span with a single carriage return or its entity equivalent (&#13) instead of two br tags to add a space between two inline sentences

Use conditional comments to insert another span that has a word-wrap:pre rule around the paragraph preceding the one with the predefined spacing to achieve consistent display in IE6/7

Use the <wbr> tag or its entity equivalent in conditional comments <![if (!IE)]> &#8203 <![endif]> to insert a conditional carriage return that will wrap long words if necessary at the position where the tag is placed. Use wbr:after { content: “0200B” } in CSS to insert the equivalent HTML entity for Opera and Safari, which do not recognize the <wbr> tag, in order to produce the effect on those browsers. Use word-wrap:break-word if Firefox 2, Safari 2, and Opera 9 are not supported.

Set generous bottom margins for paragraph tags globally for create consistent and maintainable leading standards

Set uniform left and right padding for container divs to create consistent and maintainable gutter standards

Set wider left margins for list items and quoted text to facilitate hanging punctuation

Inline text needs the same font-size, line-height, vertical alignment, padding, border, margins and position values to line up consistently across browsers

Use ‘text-indent: 0′ on elements that are specified ‘display:inline-block’ to avoid inheritance and hasLayout issues since IE6 crops text moved outside the container due to negative text-indent values

Use a wrapper with the desired font-size when setting margins, letter-spacing, or text-spacing in IE7, since the font-size of the parent element is used to compute the relative property values instead of font-size of the element itself

Specify the line height to be the same as the height of the box to align text vertically

The baseline is an invisible line onto which all type characters sit.

Descenders are lowercase letters that hang below the baseline, including j, g, y, and p.

Baseline shift involves moving characters up or down in relation to the baseline to align entities, bullets, brackets, numbers and other font-based graphics with letters

Use relative positioning and minor top and bottom movements to implement baseline shifting with CSS

Text in Firefox 3 Mac with opacity set on it looks messed up, and text in Firefox 2 Mac with opacity set has reduced contrast

Use CSS3 selectors, generated content, and Unicode values to dynamically surround content in blockquotes with quotation marks:

blockquote > *:first-child:before{content:"\201C";}
blockquote > *:last-child:after {content:"\201D";}

Use the writing-mode property with a value of tb-rl value to rotate text 90 degrees clockwise and align it to the right in IE, and using the transform property with a value of rotate(90deg) in standards browsers

Dimensions

Use 100% as the height of the html and body tags to create a point of reference for a top level container div with height 100%

Use px as the measurement for container divs, since ems are calculated inconsistently between different versions and brands of browsers

Use the width property instead of the size attribute of the input tag to set the length of a text box

Avoid defining conflicting values(colors, width, height) for the adjacent margins or borders of neighboring elements

Inline elements cannot have a defined width or vertical margins unless the display is set to block

Inline elements only have vertical padding if they are wrapped in another inline element, like so:

p > span { padding: 10px 0; background: lime; }
span span { background-color: black; color: white }
<p>
  <span>
    <span>
      Vertical Padding!
    </span>
  </span>
</p>

Width and height only apply to block or absolutely positioned elements

Add display:block and 100% width/height to anchor tags within table cells or vertical lists to make the click/hover area expand to the width of the parent element

Add display:block and width/height to image tags to maintain placeholder blocks for missing image files

Width goes on the parent, and then borders and padding go on a width:auto child

Never use a measurement for the line-height property

Use paragraphs instead of divs when width and height don’t take effect

A element with a percentage height is defined based on the height of its container. If the container has an undefined height (the default value of auto), then the element collapses to auto as well and shrink wraps its content. As a result, you cannot nest an 100% height element within an 100% height container and expect it to fill the container.

An absolutely positioned element can be set to 100% height of its relatively positioned parent in all browsers except IE6. In IE6, height:100% collapses to height auto which is line-height, therefore you need to set the absolutely positioned element to bottom:0 and give it a height which is deliberately larger than the parent container could be, an use overflow:hidden on the parent to truncate the excess content

Box Model

The horizontal space occupied a static block element is always as wide as its container, no matter what it looks like. The total space is the width plus padding, margins, and borders, so if a div in a 100px container has 10px margins outside, 5px padding inside, and 5px borders on each side, the width will automatically be 70px.

When both margins and the width are explicitly set and the horizontal space is larger than the container, the browser overrides the value of margin-right and sets it to a negative value to avoid stretching the container. This creates overflow into the following inline block, which will result in overlap or obscured content depending on the overflow value.

Padding and borders cannot be set to auto, and so cannot be overridden by the browser.

Use top borders to separate table cells instead of bottom borders if every cell will need a border except the last. It’s easier to reset the top border of the first list item rather than check if every subsequent item is the last item, then remove it’s bottom border dynamically. Do the reverse if every cell will need a border except the first.

Use margins to apply spacing outside of borders between containers, and padding to apply spacing inside of borders between content

Vertical margins are collapsed in the normal flow between static block elements, so the bottom margin value of one container is compared to the top margin of the container beneath it, and the larger of the two values is used as the total space between the two elements. Elements that are inline-block in standards browsers or have hasLayout in IE do not collapse their margins. A nested block does not collapse margins with its container if the container’s overflow is not visible

Vertical alignment is only applied to inline elements or table cells, so use it along with display:inline-block or display:table-cell with a display:table parent when vertically centering block elements

Left or right margins set on inline elements are applied to the beginning or end, respectively, of the element even with word wrapping. A left margin will cause an indentation offset at the beginning of the element, and a right margin will create blank space after the end of the element, useful for artificially pushing any subsequent text to a newline.

Use margin-right:xxx where xxx is the number of pixels between the end of the last sentence and the container to create a line break for a span of text without inserting a break tag

Use margin-bottom instead of the <br> tag to emulate empty line breaks between block level elements. Find the number of pixels equal to a single line, then multiple it to get double, triple, or whatever spacing required

Reduce margins instead of increasing padding for cross browser consistency

Use position:relative; and display:inline-block for IE6 and IE7 on the content div and overflow:visible on the container when using negative margins on nested divs for cross-browser consistency

Avoid padding and borders on inline text for cross browser consistency

Vertical margins only apply to block elements

Set both the left margin and left padding of the list elements and avoid line-height for consistent placement of bullets across browsers.

Use margin-right:auto with margin-left:0 and text-align:left to left align an hr tag across browsers

Don’t use percentages for margins or borders

Use overflow:hidden to avoid scroll bars within a div and the expanding box problem in IE

Use width: auto and overflow: visible on button elements to avoid extra padding in IE

Use overflow:auto to avoid scroll bars within a textarea in IE

Use the HTML 4.01 Transitional doctype without a URL to force quirks mode on all browsers

Use the HTML 4.01 Strict doctype to force strict on all browser except IE

In the W3C box model, element width excludes padding and borders

In the classic IE box model, element width includes padding and borders, giving extra spacing between containers, but IE6 and later use the W3C box model when in standards compliant mode

IE6 always stretches boxes to display overflow content, while other browsers do not, so use overflow:hidden in IE6 to avoid this behavior

IE6 doesn’t implement overflow:visible correctly and needs width to be set on the container element to support overflow:hidden

IE6 can emulate overflow:visible by using a relatively positioned wrapper div that includes a hasLayout trigger and negative margins equal to the size of the overflow content minus the container

IE6 and IE7 don’t implement overflow:hidden and overflow:auto correctly with relatively positioned content unless give position:relative is set on the container as well

IE6 gives the first element of an li tag an irregular margin, so use display:none and skip content for that element

Use -moz-box-sizing: border-box; to emulate the IE box model in Firefox. Use box-sizing: border-box; to emulate it in Safari and Opera

Use -ms-box-sizing: content-box; to emulate the W3C box model in IE.

To remove the horizontal scrolling bar, declare overflow-x: hidden; as a style for the body tag

Negative margins make an element wider than usual. If a top margin is negative, it has the effect of dragging the element upward. If a bottom margin is negative, then anything which follows the element will be pulled upward, which could partially or completely obscure the element itself, since user agents are not required to re-flow documents based on negative-margin

If all paragraphs have a five pixel vertical margin, and one paragraph follows another, there will be five pixels between them, due to the collapsing of adjacent vertical margins. For example, consider a heading immediately followed by a paragraph and given the following styles:

H1 {margin-bottom: 0.5em;}
P {margin-top: 0.75em;}

The margins are collapsed together, leaving 0.75em between the H1 and the paragraph.

Any negative margin is added to the maximum of any positive adjoining margins. This reduces the positive margin (since adding a negative value is the same as subtracting a positive value) to arrive at the separation between the two elements. For example:

.one {margin-bottom: 1em;}
.two {margin-top: -0.75em;}
The result of these styles is a quarter-em of blank space between the two paragraphs (assuming .one is immediately followed by .two, of course).

Use negative margins to make elements wider than they otherwise could be, or to cause an overprinting effect

If left or right margins are set on inline elements, then they are applied to the very beginning or end (respectively) of the element, even if it breaks across multiple lines. Thus, a left margin will cause a visual offset just before the beginning of the element, appearing to push it to the left. Similarly, a right margin will create blank space after the end of the element, appearing to push any following text to the left.

Background Colors and Images

Use the opacity property to create a rollover effect instead of swapping images. Make sure the elements have haslayout in IE6 and IE7 or opacity will not be applied

Use background-color on a nested block to override a background-image set on the containing block

Use the background-position property to move an image to one of the eight compass directions behind the foreground text or image

Use the background-position property to change the hover state of links with background images using CSS sprites

Use background:transparent for rollovers where the parent element includes the image in the hovered position

Use background-image URLs on divs instead of image tags for images that are not content related or part of hyperlinks

Use background-image URLs on inputs instead of the image type attribute or button tags for styling buttons that will function without CSS or images enabled for accessibility by mobile and text browsers

Use background-attachment: fixed to glue an image to the body or a container element so it is visible when scrolling through the content of the element

Use display:list-item and list-style-image to create printable CSS background graphics for headers. Use ‘list-item-position:inside’ to move the image inside the header, and letter-spacing to move the header text off the body of the page

Use keywords or numeric values exclusively instead of mixing measurements when setting background-position values, such as background-position:right bottom or background-position: 100% 100% instead of background-position: 100% bottom

When using shorthand to set all background properties in one declaration, use the following order for consistency and compatibility across browsers:
background-color
background-image
background-repeat
background-attachment
horizontal position
vertical position

Use a span with an id that matches the name of the image file referenced in its background-image declaration to create a background image that acts as a foreground image. Nest an image tag inside the span which displays a transparent one pixel image as a placeholder for a future foreground image. Use the dimensions of the file in the span img CSS declaration, and width/height=1 as the dimensions of the img tag attribute fields

Defining the width of a static box that follows a float makes IE6 display differently than any standards compliant browser.

Don’t bother with quotation marks around background image URLs.

Use a ridiculous line-height or negative margin along with overflow:hidden to hide text replaced by images

Don’t use ems as the measurement value to hide text

To use an image for an hr tag, wrap it in a div that uses the image as a background URL and set the hr to display:none;

When using percentages to set values for the background-position property, a point in the image and a point in the container are mapped to each other. So setting background-position: 14% 84% takes the pixel 14% across and 84% down the background image and places it at the pixel 14% across and 84% down the area of the container. This means if your graphic is the same size as your HTML element, changing the percentage will make no difference whatsoever.

When using MHTML:URIs to display Base64 images for IE, make sure to save the encoded images in a .mht
file and reference it in the URL to separate the data from the stylesheet and IE specific content from
other browsers

IE6 loads image tag sources before it loads background images from the CSS

If a container with overflowing content and overflow:scroll has content with background-attachment: fixed, the parent background moves with the scrolling of the element in IE7

If a container with overflowing container has overflow:scroll and background-attachment: fixed, this inadvertently emulates background-attachment:scroll in IE6 and fixes the aforementioned bug in IE7

Visual Interaction

Use cursor:pointer to emulate the onmouseover event cursor change

IE6 supports the :active, :hover, :focus, :link, :visited link states

Use :active instead of onclick events and :hover instead of onmouseover events when possible

Use “a[href=www.mysite.com]” to target elements with specific attribute values(CSS2 Attribute Selector)

Use “ul > li{…}” instead of “ul li{…}” to only target the first level children of a tag instead of all nested descendants(CSS2 Child Selector)

Add absolutely positioned elements within link tags and reference them in hover definitions(ex. A:hover span{…}) to create rollover dropdown menus without JavaScript

Use a border color which is equal to the background color as the default value then change it in the hover state to create a rollover effect without shifting the content. Decrease the desired padding by the size of the border to adjust for it always being hidden in the background instead of inserted and removed dynamically.

Use a:active, a:focus{outline:0;width:0;height:0;} to remove the dotted line around clicked links

Use img {border:none;} to remove the border around images

Use :link,:visited to style links without styling anchor tags

Use cursor styles and image maps to extend the click area of links to cover the dimensions of their parent elements without using JavaScript

The top and left parameters of the clip property remove any pixels with coordinates above or before the specified values, based on the top and left edges of the element. By contrast, the bottom and right parameters remove any pixels located below or after the specified values, based on the top and left edges of the element. The values for bottom and right must be higher than the values of top and left in order to see any of the layer. The clipped element must be absolutely positioned for the clip property to work, so use a relatively positioned container around it. Specifying the height of the container keeps the next line from overlapping with the clipped areas.

Use rel=”external” for all external links and a[rel~="external"] { target-new: tab; } (CSS3 Attribute Selector) to open links in a new tab

Use { target-name: modal; } (CSS3 Attribute Selector) to open links in a modal box

Use matching light colors for the top and left border and matching dark colors for the bottom and right border of a link. On hover, flip the color pairs and relatively position the link down and to the right by one pixel to generate a simple 3D button effect.

Use :: notation (double colon notation) for pseudo-elements(::first-line, ::first-letter, ::before, ::after, etc.) to distinguish them from pseudo-classes(:active, :hover, :focus, :link, :visited, :first-child, etc.). For compatibility with IE6/7, use single colon notation for both or IE specific styles.

If a container hasLayout(fixed width/height, inline-block,float), then block level anchors within will not have proper hit detection unless one of the links also includes a hasLayout trigger (zoom, inline-block, fixed height) for itself or a child element, or includes an image as a child element. hasLayout on the block level anchor itself
may cause margins to disappear, so avoid vertical margins in that situation

If a block level link is absolutely positioned over content, it will not have proper hit detection unless it has a defined background. You can make the background transparent or use opacity to make the content visible

Stylesheet Organization

Use a CSS Validator to ensure that typos and conflicting declarations aren’t causing bugs on your page

Reference IDs and classes directly without prefixing them with parent tag or class names

Don’t use the same class to set both dimensions and other box model rules including margins, borders, and padding to avoid limiting the reuse of size or spacing rules among different elements

Use a simple class selector, such as .new{ font:bold;} instead of creating complex descendant selectors to define a single property, such as .menu .title .new{ font:bold; } to maximize to readability and reusability of the codebase

Don’t use DOM property names (length, item, namedItem, tags, urns) as ID values since they will cause JavaScript conflicts in IE since it considers property names to be reserved words

Don’t use attribute name values as ID values since they will cause JavaScript conflicts in IE. For example, using “description” as an ID value may conflict with the description meta tag.

Create unique new classes instead of parent dependent subclasses

Copy common properties, such as colors and font size, to new classes as a preventive measure so that an element is not dependent on multiple classes due to a single property of each one, since the class references in the HTML may end up looking like inline styling. This also helps avoid inheriting unneeded properties, such as padding and margins, and subsequently needed to reset these properties in new classes

Minimize usage of the descendant selector (e.g. #parent .child) and the child selectors when styling elements to avoid long lookups of the DOM tree

Define classes to style block level elements(.content) instead of using tag references by ID (#main p) to make them independent of their parent elements

Define state changes in CSS by prepending copies of existing selectors with semantic class names that map to JavaScript functions, then append the class name to the documentElement when the DOM event is triggered

Avoid semicolons on the last style declaration to avoid accidentally typing the end bracket before the semicolon and generating an error

Avoid naming conventions in which a class describes the property it invokes so that the style sheet does not become a one-to-one mapping of names to functionality which leads to HTML code which resembles inline styling with multiple class references for every element.

Use styles to set properties for tables instead of table tag attributes for cross browser consistency

Add subclasses for common needs, such as highlighting the first or last item in a list, hiding and showing comment text, emphasizing the current navigation selection, and switching star rating colors on and off

Use semantic ID names for standard layout components, such as banner, logo, badge, screenshot, thumbnail, breadcrumbs, navigation, sidebars, marquee, subnav, content, gutter, headmargin, footmargin, sidemargin, baseline, overlay, fold, ads, widgets, and audio/video players

Use semantic class names for standard prose components that may need specific styling, such as sentence, phrase, clause, salutation, lead-in, suffix, prefix, anagram, homonym, contraction, gerund, idiom, interjection, onomatopoeia, timespan, etc.

Use semantic class names for standard article components that may need specific styling, such as headshot, caption, mugshot, masthead, folio, subhead, dateline, byline, topic, bio, ticker, alert, boilerplate, dropcap, slogan, keyword, tease, sample, snippet, sidebar, boxscore, ranking, standing, poll, addendum, soundbite, pullquote, plugs, followup, letterhead, etc.

Use semantic class names for essay components that may need specific styling, such as objective, excerpt, aside, citation, footnote, topic, annotation, summary, table of contents, etc.

Style fonts and colors for standard layout components first to avoid redundancy and take advantage of the cascade when defining nested elements

Reset styles at the beginning of the style sheet to overwrite inconsistent defaults across browsers

Remove redundant and obsolete styles when moving test code to production

Use classes instead of IDs for any code intended to work inside the sandbox of a third party API, since IDs may be stripped out to avoid conflicts

Use JCSS for JavaScript, CleverCSS for Python, LessCSS for Ruby, or Conditional CSS for PHP to add CSS variables to your stylesheet using browser or server-side scripting

Use conditional comments to create an IE container div which you can use to reference IE specific styles instead of loading a separate stylesheet

ex.
<!- -[if IE 7]>
<div class=”ie”>
<![endif]>
<!- -[if lte IE 6]>
<div class=”ie ie6″>
<![endif]>
(content)
<!- -[if lte IE 7]>
</div>
<![endif]>

div.nav { margin-left: 20px; }
.ie div.nav { margin-left: 40px; }
.ie6 div.container { height: 100%; }

Debugging

Test in at least four browser engines (Gecko, Webkit, Trident, Presto) each time you make a change
to avoid massive debugging efforts at the “end” of a layout styling task

Only use classes for a collection of elements that may appear in multiple sections of a single page, otherwise just reference the collection using the ID of their container

Validate the HTML and CSS code to make sure the markup is not breaking the layout and the style rules do not contain any syntax errors

Make sure that margins and paddings have been reset if there is mysterious whitespace between elements

Make sure that there are no line breaks or whitespace between an anchor tag and a nested image or span if the layout is mysteriously broken

Make sure that all four corners of each element is visible using the a browser-based box model tool (Web Developer Toolbar, IE Developer Toolbar, Dragonfly, Display Element Info Bookmarket) to identify overflow related issues. If the width is too large and the right border is missing, reduced the fixed width of the element. If the height is too large and the bottom border is missing, turn off overflow if the content is not truncated, otherwise reduce the height or reposition any neighboring elements with absolute positioning, relative positioning, or negative margins that are obscuring the content

Use applied styles context menu in the IE Developer Toolbar to see which rules in the cascade are overwriting the ones you want

Copy and paste generated source in HTML validator for pages where the validator doesn’t work on the URL

Make sure that padding for any child elements is not forcing the container to expand outside of its defined dimensions, and reduce the dimensions accordingly if you cannot avoid setting both padding and width or height on the same element

Make sure to test the layout with and without toolbars in the browser chrome to make sure no min-height bugs are triggered by adding or removing menus from the browser

Make sure that styles you have defined are not being overwritten by existing styles with more specificity or those defined later in the CSS code by increasing the selector weight using references to parent classes or IDs

Make sure to use Firebug or Web Inspector to verfiy mini-resets of localized CSS rules and increase the selector weight if necessary to override cascading that may inadvertently cause mysterious layout issues

Make sure to increase the selector weight of IE specific CSS rules when doing so for universal styles

Make sure that the width and height dimensions of the container allow enough space to provide the vertical or horizontal positioning declared in the CSS code

Make sure that the width and height dimensions of all floated elements fit within the constraints of the container

Make sure that the width of right aligned content such as label copy is only as large as needed to avoid using left margins or padding for alignment since it may not be consistent across browsers

Make sure that floated elements with wrapping content have a defined width and proper text alignment

Make sure that any containers that expand on :hover have the a default width and height which is greater than or equal to the size of any nested elements

Make sure that fixed-width containers use overflow:hidden so shrinkwrapped nested blocks don’t cause margin collapsing in older versions of Firefox

Make sure that all inline elements are absolutely positioned or contained in block level elements

Change the position attributes of the container to make sure it allows absolute or relative placement of nested elements

Create a copy of the template and remove all divs except the misaligned one and its adjacent divs to debug positioning issues

Put a container div around block level elements that don’t respond to display:inline or display:inline-block declarations

Remove margins from inner divs when debugging ignored positioning values in absolutely positioned divs

Remove all inline text and start with a non-breaking space as the placeholder content to debug width and height issues

Set margin, padding, font-size, and border size to zero for debugging unseen inheritance issues

Use a display:block with a fixed height if margins are inconsistent for inline text in situations such as creating a header using markup and one-pixel margins to create rounded corners

Use IE specific styles when absolutely positioned elements or margins are inconsistent with other browsers

Use obvious background colors to highlight misplaced or misaligned nested elements when debugging
inner divs

Use inline styles and remove ID and class references to display elements that are invisible due to an unknown CSS error

Use word-wrap:break-word(CSS3 Property) or wbr(and its alternatives) to break lines within long words to prevent overflow of an unbreakable string from causing horizontal scrollbars or inadvertent wrapping of blocks to a new line

Use table specific font rules in IE5 set since those applied to html and body tags do not cascade to table elements

Use divs instead of paragraphs when margins don’t take effect

Use divs instead of paragraphs to avoid the inherit vertical margins between paragraphs

Use display:inline on an absolutely positioned elements to avoid hasLayout issues

Use margins to move absolutely positioned elements instead of directional shifts

Use border-collapse: collapse; and border-spacing:0 to remove gaps between table columns

Use border styling on the td element instead of the tr element after doing the above to create grid lines on a table

Use empty-cells: hide to remove borders from empty table cells

Use position:relative on inline text and position:absolute on block-level containers and media

Use inline-block to give hasLayout to a relatively positioned container

Create more classes with specific names instead of creating more complex parent=>child references

Make sure there’s not a more specific CSS rule or one that comes later in the style sheet which is overriding the desired effect

Make sure the there’s not a number at the beginning of the ignored class or ID name

IE will only change the state of a hovered child element when something changes on the anchor tag, so use a redundant effect like a:hover{ visibility:visible; } if something like a:hover span { display:block; } doesn’t work

IE will only change the state of a hovered child element that is referenced using a parent class or id if a property is set on the anchor tag that hasn’t been declared in any other pseudo classes for that anchor, such as text indent:0, float:none, direction:inherit, visibility:inherit, white-space:normal, etc
ex.
.class a:hover span{} needs .class a:hover{visibility:inherit;}

IE will increase the width of a container with an italicized font style so use overflow:hidden to avoid inconsistent wrapping if possible

If links on a page are clickable in IE only, look for an absolutely positioned element that overlaps the links and raise the z-index value of the link container or reposition the layout so the overlap does not happen

If the property value for a group of elements doesn’t work, redefine that property value for one of those elements to see if a comma is missing or an unsupported selector nullified the entire rule

#business_photo, .sentence, .instruction, .list > li { padding-bottom: 24px; }

/* Redefine the same padding value because the descendant selector nullifies the above line in IE6 */
#business_photo { padding-bottom: 24px; }

If neighboring elements are mysteriously repositioned when an event or hover triggers the display or a submenu or other hidden content, make sure that content is not relatively positioned in external CSS, inline CSS, or generated JavaScript attributes.

If margins between a series of lists with headers are inconsistent due to special cases such as scrollbars for overflow in long lists or different margins for the first or last list, remove margins from the lists themselves and put them on the headers and use padding at the top and bottom of the container to handle spacing between the first or last list and the borders

If a border does not show up on around an element, make the color black or white to see if the color is too light or dark to distinguish from the background

If a div is being pushed beneath its specified position to a new line, use the mouse to select the content within the div to see if the dimensions of a block element within it are causing overflow outside the container. Make sure to set the width of any forms within the container in addition to validating the HTML to make sure no block tags are missing or inline tags have block tags nested within them.

If a hover or visited state of a hyperlink is not working correctly, do the following checks:
-Make sure the pseudo classes are defined in the correct order
-Make sure the pseudo classes don’t share the same definition as a less-specific element, like a:hover{color: #ccc;} and .mylink:hover{color: #ccc;} since the browser will group them together and parse the less-specific rules in the cascade before the more specific rule, such as .mysite{color: #eee;}. If this is the case, add a reference to the parent container to the pseudo class rules, for example .mymenu .mylink:hover{color: #ccc;} to increase the selector weight.
-Make sure the pseduo classes are defined or the element selector instead of the class selector, for example .nav a:hover vs nav a.submenu:hover. This may not work in IE6.
-Make sure the rules are defined in the proper order, which is the following:
1. :link, :visited
2. :hover, :focus
3. :active

Since a link can simultaneously be in the :visited, :hover, and :active states, and they have the same specificity, the last one listed wins.

Increase or decrease the text inside a container to make sure it wraps text and resizes properly

Increase or decrease the font size of the browser a few times to see how it affects your backgrounds and margins, especially for text used in headings and navigation

Apply classes to different elements to make sure each class is not dependent upon a specific tag

Include several block elements such as a few paragraphs and a large list inside a div to see if it breaks the flow of the container

Set position:relative on floated elements if they are not visible in IE6 or IE7

Set a fixed width or height for a data table cell if word wrapping causes any nested containers with relative dimensions to expand. If there is a div container with a percentage width inside any table cell, content that forces word wrapping in another cell causes the relative width of the div will grow in IE6 and IE7 to match the overflow width of the table cell if an explicit width or height is not set on the cell to contain the content

Reset the line-height of an element if it stretches larger than its defined height in IE

Use clear to break an element away from a floated sibling and wrap it to a new line

Separate HTML structure and CSS design by developing the naming conventions and organization of the container styles without thinking about the content

Create a reusable library of headers, footers, submenus, navigation bars, lists, forms, and grid layouts

Use consistent semantic styles

Design modules to be transparent on the inside

Extend objects by applying multiple classes to an element

Use CSS reset styles, web-safe fonts, and grids on all projects

Avoid location dependent styles that break outside of the cascade

Don’t sprite every image together

Avoid specifying what tag a class refers to through the class name

Avoid using IDs to style content within the main layout containers

Avoid using images to replace text

Avoid drop shadows and rounded corners over irregular backgrounds

Avoid using 1px dotted borders in IE6 since it is buggy and will display a dashed border. Use an IE6 specific style of 2px border-width and a lighter shade of the desired color to offset the larger pixel size.

Avoid using any vertical-align value besides top or bottom for form elements

Only use the !important declaration to create user style sheets or to override an inline style if the HTML markup is not editable. The !important declaration must follow the value of the property that it intends to give weight to. Since inline styles can be added to any HTML tag, using the style attribute selector is the only way to override those styles if a class or ID attribute is not defined for the element, as in the following example:

div[style]{ background-color: #f00 !important; }

Layout Emulation

Use a CSS3 multicolumn list or inline-block machinations to emulate newspaper column layout for articles

Use absolutely positioned wrapper divs to create equal height columns using the following steps:

- Create a container div and set it to be relatively positioned
- Create content div columns using floats or inline-block
- Place an absolutely positioned div as the last element inside the container div
- Set the absolutely positioned div to {height: 100%; bottom:0}
- Set the width of the absolutely positioned div equal to the width of the first content div column
- Set the left offset of the absolutely positioned div so that it overlaps the first content div column
- Set the desired border and background color of the absolutely positioned div
- Repeat this step for the remaining content div columns
- Use position:relative and z-index: 2 for the static content divs or paragraphs within the container so that they will not be obscured by the absolute elements
- For IE6, give the absolute columns are ridiculously large height so that they will extend to the top of the page, but remember to give the header position:relative and z-index: 2 to hide the border and background colors of the absolutely positioned divs

Use an alternative style sheet if no cookie exists for your site to load the home page with just the logo, set the visited cookie, and links to the standard style sheet which reveals the hidden content as an alternative to the traditional Flash based splash page

Use a hover effect for the entire navigation menu, then follow it with a overriding effect for the currently hovered link to accentuate that link, while deemphasizing the rest
ex.
/* Anti-Rollover for un-hovered nav links */
.nav:hover a { opacity: 0.5; }

/* Rollover for nav links */
.nav a:hover { color: #f7f7f7; background-color: #86618C; opacity: 0.9; }

Use CSS3 generated content to add the URL of the href attribute in parentheses next to the hyperlink text in the printable view of a page to emulate internal citations
ex.
a:visited:after { content: ” (” attr(href) “) “; }

This is also useful to extract URLs from a broken or long page:

body * { visibility: hidden; }
a:link:before, a:visited:before { content: attr(href); }

Use the Online Character Database to find the hex code for a numeric HTML entity value. Prepend the hex code with a backslash to generate it as :before or :after content in CSS

Use relatively positioned wrapper negative offsets and slightly varying background colors to create drop shadows

Use a descriptive class name for each navigation link and add a list of classes to the body tag to match each navigation class in order to style or disable the hyperlink for the active page

Use display:block and display:inline-block on nested span tags to create semantic forms with full control of spacing, word wrapping and dimensions of fields and labels

Use the :before pseudo-class and the title attribute selector to generate a shadowed letter of a span element with the title equal to the text. Set the span to display:block and position:relative, then adjust the positioning to push it over the letter and slightly offset to the left to emulate a drop shadow.

Use server-side code to add a CSS class which defines the height in IE6 equal to max-height in other browsers after a set number of loop iterations to emulate conditional scrolling of a list using overflow:y

Use the following steps to emulate hover triggered dropdown navigation items in IE6:
-Create a copy of the top level link list item in a conditional comment and nest a table within the link of that copy
-Place the child level list items outside conditional comments in their natural order within the td tag of the table
-Close the table and the copy of the list item after the last sub item
-In the CSS file, relatively position the copied list item and its children
-Move the list parent down and its children up to match the natural position of the submenu in other browsers
-Use display:none as the default state of the nested table and its child links
-Use display:list-item as the hover state of the table and its child list items
-Use the content area color as the default background color of the child links
-Use the navmenu color as the background color of the child links during the hover state of the parent link
-Use the hover color of the navmenu links as the background color of the child links during the hover state of child links within the hover state of the parent link

Use the following alternative to emulate hover triggered dropdown navigation in IE6:
- Create three floats: a container div, and parent hyperlink, and a subnav div with zero margins and padding
- Create subnav links within the subnav div
- Set the parent and subnav links to display:list-item or display:block
- Set the width of the parent and subnav links equal to that of the parent div so the entire box is clickable
- Set the desired height of the parent and subnav links
- Set the top margin of the container div to a large negative number to hide the links offscreen
- Set the top margin of the parent link to the positive equivalent of the container div to move it into view
- Set the right margin of the parent link to one pixel less than its width
- Set the right margin of the subnav links to negative one pixel
- Set the right margin of the parent nav to zero to offset the negative top margin on the submenu
- Set the are right margin of the subnav links to a positive value so that they are wider than the space allowed which forces each subnav link to drop below the parent link

.container, .parent, .sub { margin:0; padding:0; float:left; }

.parent, .sub a { display: list-item; }

.container, .parent, .sub a { width: 200px; }

.parent, .sub a { height:25px; }

.container { margin-top:-1000px; }

.parent { margin-top:1000px; margin-right:-199px; }

.sub a { margin-right:-1px; }

.parent:hover { margin-right: 0; }

.sub a:hover { margin-right:1px; }

.parent:hover, .sub a:hover { color: #bbb; }

<div class=”container”>
<a class=”parent” href=”http://www.yahoo.com”>Parent</a>
<div class=”sub”>
<a href=”http://www.hedgerwow.com”>link 1</a>
<a href=”http://www.stevesouders.com”>link 2</a>
<a href=”http://www.phpied.com”>link 3</a>
<a href=”http://www.nczonline.net”>link 4</a>
</div>
</div>

Use thick borders to create a diagonal effect in CSS using the following steps:
- Set one border color equal to the body background to create the illusion of invisibility
- Set the adjacent border color to be whatever
- The intersection between the two borders is rendered as the diagonal edge
- Transparent does not work as a distinct color in IE

Use a nested span within an anchor tag to create CSS tooltips using the following steps:
- Create a relatively positioned anchor with an absolutely positioned span as a child element
- Give the span visibility:hidden by default and reposition it to not overlap the parent
- Give visibility:visible to the span on :hover. Give it to the anchor as well for IE6 to trigger the pseudo-class

Use an empty span in the anchor tag of each li to emulate :hover on a ul in IE6 using the following steps:
- The ul will be set to position:relative to act as the bounding box of each span
- The spans will be set to position:absolute; bottom:0 to cover the bottom edge of the ul
- The spans will be the given desired hover background color and a height large enough to always fill the ul
- The ul will be set to overflow:hidden to hide the extra height of the spans
- The background color of the span will then effect the ul on :hover

Use nested spans to created irregularly shaped anchors without image maps with the following steps:
- Use the same setup as above to nest spans within anchors
- Set the anchors and the spans to be absolutely positioned
- Set the ul to be relatively positioned
- Set a single background image for both the anchors and spans
- Reposition the anchors and spans so that the bounding boxes for the anchors do not overlap
- Change the background position of the anchors and spans on :hover to match the rollover state

Use a nested placeholder div to emulate min-width in IE6 using the following steps:
- Create a container div and set min-width to the minimum and width to the maximum
- Create an empty div within the container with zero height and width equal to the min-width value
- Make sure overflow is set to visible for the container div and hidden for the placeholder div

Use two placeholder floats with opposing directions to emulate max-width in IE6 using the following steps:
- Create two divs with width:50% and height:0 so that together they cover the entire horizontal space without taking up the vertical space within the container div or the body
- Set one float:left and margin-right:-xxx, the other float:right and margin-left:-xxx (where xxx is half the desired max-width to make room for the content div)
- Create a content div with hasLayout using zoom:1, display:inline-block, or float:left; to force the text to wrap once the negative margin space between the floats is full
- Set the content div to overflow:hidden to force the text to wrap on standards browsers
- Set the floats to height:1px to get the negative margins to work on standards browsers
- Make sure to use word-wrap:break-word to prevent long words from stretching the content div beyond the max-width

.leftedge { float:left; margin-right:-200px; }
.rightedge { float:right; margin-left:-200px; }
.leftedge, .rightedge { width:50%; height:1px; }
.content { overflow:hidden; padding:10px; border:1px solid #000; }
.ie67 .content { zoom:1; word-wrap:break-word; }

<!–[if lt IE 8]>
<body class=”ie67″>
<![endif]–>

<![if (!IE) | (IE 8)]>
<body>
<![endif]>
<div class=”leftedge”></div>
<div class=”rightedge”></div>
<div class=”content”>fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffI’m at most 200px
</div>

Use a relatively positioned wrapper for absolutely positioned content plus the clip property to emulate max-height in IE6 using the following steps:
-Set the container of the max-height div to position:relative
-Set the max-height div to position:absolute and overflow:hidden;
-Set the desired max-height for standards browsers
-Convert the max-height to the format of the clip property for IE6
-Use zero for the first and last parameters, and set the third parameter equal to the max-height
-Use the second parameter to emulate max-width as well if needed

.wrapper {  position:relative; }

.content{ overflow:hidden; position:absolute; }

.content { max-width:8px;  max-height:12px; }

/*
The first and last values are the top and left starting points
The second and third values are the right and bottom ending points
*/
.ie6 .content { clip:rect(0 8px 12px 0); }
<!--[if IE 6]>
  <body class="ie6">
<![endif]-->

<![if (!IE) | (gte IE 7 )]>
<body>
<![endif]>

    <div class="wrapper">
        <div class="content">
            <img src="http://mozilla.org/favicon.ico">
        </div>
    </div>
    <div>p</div>
</body>

Use overflow-y and absolute positioning to emulate fixed positioning in IE6 using the following steps:
- Create an absolutely positioned div and give it the desired top and left coordinates on the page
- Set html{overflow-y:} to be hidden or visibile instead of the default auto or scroll to eliminate the scrollbar
for the absolutely positioned div
- Set body{overflow-y:} to be auto or scroll to insert a new scrollbar for the body content
- Set body{margin:0; height:100%} to make sure the content scrollbar goes the length of the page
- Set top and left margins on the body to separate the content from the absolutely positioned div
- Make sure the doctype is set to trigger Standards Mode in IE
- If the doctype is not set, move the html rules to the body tag, and the body rules to a wrapper div

html { _overflow-y: visible; *overflow-y: auto; }

body { margin:0; margin-left: 14em; }

#fixedbox { position: fixed; top: 1em; left: 1em; width: 10em; }

#fixedbox { padding: 0.5em; border: 1px solid #000; }

#container { height: 2000px; }

.ie6 { overflow-y: auto; height: 100%; }

.ie6 #fixedbox { position: absolute; }

<!--[if IE 6]>
  <body class="ie6">
<![endif]-->

<![if (!IE) | (gte IE 7 )]>
<body>
<![endif]>

<div id="container">
Fixed box
</div>

<div id="fixedbox">
Homer
</div>

Use the aforementioned fixed-positioning pattern plus the following changes to create a modal dialog in IE6:
- Set the absolutely positioned div to top:50%; left:50%;
- Add position:relative and the desired opacity to the container div

Use absolute positioning and z-index to create a sticky footer div at any resolution using the following steps:
- Create a footer div with position: absolute; bottom: 0; and the desired height
- Set the z-index to 2 or something greater than the body content so it is not obscured
- Set the padding of the footer to add whitespace between the content bottom and the window bottom
- Create a container div that wraps the body content with position: relative; min-height: 100%;
- Set the html tag, body tag, and container div to height: 100% for IE6
- Add bottom padding to the main content div that is equal to the width plus padding of the footer

Use vertical-align, text-align, display:table and inline-block to center static content horizontally and vertically using the following steps:
- Set the html tag, body tag, container div, and a placeholder div to height: 100% as a vertical reference
- Center the container div horizontally with display:table; plus margin-left: auto; margin-right: auto; in standards browsers
- Center the container div horizontally with text-align:center in IE6 and IE7
- Realign the content with text-align:left in IE6 and IE7
- Center the content vertically with vertical-align:middle on it and the placeholder div
- Set the content to display:table-cell in standards browsers for vertical-align to take effect
- Set the content and placeholder divs to display:inline-block in IE6 and IE7 for vertical-align to take effect
html, body, #container { height: 100%; }

/* Horizontal Centering */
#container { display:table; margin-left: auto; margin-right: auto; }

/* Vertical Centering */
#content { display: table-cell; vertical-align: middle; }

.ie67 #container { text-align:center; } /* Horizontal Centering in IE */

.ie67 #placeholder { height: 100%; }

.ie67 #placeholder { vertical-align: middle; } /* Vertical Centering in IE */

.ie67 #content, .ie67 #placeholder { display: inline-block; }

.ie67 #content { text-align:left; } /* Realign Centered Text in IE */

<!--[if lte IE 7]>
  <body class="ie67">
<![endif]-->

<![if (!IE) | (gt IE 7 )]>
  <body>
<![endif]>

<div id="container">
<span id="content">
Horizontally and Vertically Centered
</span>

<!--[if lt IE 8]>
<span id="placeholder"></span>
<![endif]-->
</div>

Use the following alternative to the aforementioned method with display:inline on the content div to center static content horizontally and vertically using the following steps:
- Set the html tag, body tag, container div, and a placeholder div to height: 100% as a vertical reference
- Center the container div with text-align:center in all browsers
- Center the content vertically with vertical-align:middle on it, the placeholder div, and a nested wrapper div
- Set the content to display:inline in all browsers for the horizontal alignment to take effect
- Set the wrapper div to display:inline in IE6 and IE7 for hasLayout to take effect
- Set the wrapper div to a width of less than 100% if the content wraps to avoid a bug in Firefox and Webkit browsers
- Insert display:-moz-inline-box before the display:inline-block declaration for this to work in Firefox 2
- Insert display:-moz-inline-box after the display:inline declaration of the content div for this to work in Firefox 2.
- Insert a fixed width div nested between the wrapper div and the content for this to work in Firefox 2
- Set that div to display:inline-block to prevent it from overriding the centering in the other browsers

html, body, .container, .placeholder { height: 100%;}

img { width:16px; height:16px; margin-left: 20px; margin-top: 10px; }

.container { text-align:center; }

/* Use width of less than 100% for Firefox and Webkit */
.wrapper { width: 99%; }

.test { width: 200px; border:1px solid #000; }

.placeholder, .wrapper, .content { vertical-align: middle; }

/* Use inline-block for wrapper and placeholder */
.placeholder, .wrapper, .test { display: inline-block; }

.ie67 .wrapper, .content { display:inline; }
<!--[if lte IE 7]>
  <body class="ie67">
<![endif]-->

<![if (!IE) | (gt IE 7 )]>
  <body>
<![endif]>

<div class="container">
    <div class="content">
        <div class="wrapper">
            <div class="test">fff</div>
            <div class="test">ggg</div>
            <img src="http://wordpress.org/favicon.ico">
            ...
        </div>
    </div>
    <span class="placeholder"></span>
</div>

References

CSS Article Compilation

Performance Impact of CSS Selectors

Extending CSS Spriting

CSS Sprites are Stupid

:hover Craft Tutorial

CSS Overview

CSS from the Ground Up

Writing Efficient CSS

CSS1 Limitations for Old School Browsers

CSS Differences between Strict and Quirks Mode

Overview of Quirks Mode

CSS Features and Changes for IE7

Standards and CSS in IE

Cascading Style Sheet Compatibility in Internet Explorer 7

CSS Enhancements in IE6

Compatibility in Internet Explorer 5.5

What’s New for DHTML in Internet Explorer 5.5 and Internet Tools

-ms-writing-mode Attribute

Introduction to Viewlink

CSS Compatibility in Internet Explorer 5.5

HasLayout Overview

Strategies for CSS Switching

Select Menu Visibility Bug in IE

Link Specificity

Moving to Standards-Compliant HTML and CSS Development

CSS Code Snippets

PNG Overlay with no Extra Markup

Web Standards and Creativity

CSS Hacks Series

CSS Concepts

Safari CSS Reference

Absolute and Fixed Positioning

Making the Absolute Relative

When Links in ULs don’t work in IE

Real Text Rotation with CSS

On Having Layout

Hack Management

How to Prevent HTML Tables from Becoming too Wide

HasLayout Triggers

Reserved ID Values

Zs not Dead

Place Layers over Flash Files or Dropdowns

Opaque Windowless Mode in Flash

Conflicting Absolute Positions

Bookend Headers

CSS Box Model

Nine Techniques for Image Replacement

IE6 Background Image Hover Flicker Fixes

The Malarkey Method

State Scope Image Replacement Pattern

IE Pseudo Element CSS Bugs

What CSS did we learn in 2007

CSS: Digging Below the Surface
Extended CSS

Horizontal Sizing in CSS

Vertical Sizing in CSS

Inline Elements and Padding

Padding, Borders, and Margins

Fixed Header and Footer Demo

A More Robust Method of Positioning a Footer

@import considered harmful

Margin Collapsing and hasLayout

Italics Creating Overflow in IE

Table Rendering

Pure CSS Popups Bug

Disabling the Font Tag using CSS

Sitepoint CSS Quiz Archive

Legacy Browser Archive

9 Comments

  1. [...] CSS Tips « Paul Sweatte This is an extensive list of some very good CSS tips. Some real gems here. (tags: css layout webdesign typography article visibility boxmodel stylesheet) [...]

  2. [...] bookmarks tagged webdesign CSS Tips " Paul Sweatte saved by 2 others     thevillageother bookmarked on 07/09/08 | [...]

  3. [...] CSS Tips « Paul Sweatte An extensive list of excellent CSS tips, all in one convenient place. Woot! (tags: css tips webdesign design) [...]

  4. [...] CSS Tips via mefogus :: good list of best practices and alternatives (w/ use cases) (tags: css webdev typography) [...]

  5. [...] Paul Sweatte’s CSS Tips – I really learned quite a bit from this great post [...]

  6. alright! thanks for the lesson… Been wondering what visibility:hidden is for…

  7. CSS Tips « Paul Sweatte…

    CSS Tips « Paul Sweatte…

  8. [...] Paul Sweatte is presenting a great list of quick tips for using CSS. The list covers topics like “Positioning”, “Typography”, “Dimensions”, “Box Model”, Background Colors and Images”, “Visual Interaction” and “Stylesheet Organization”. Great resource! 04.13.08 | (Click thumbnail to visit the site!) If you like this site rate it here: [...]


Sorry, the comment form is closed at this time.

Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.