CSS Tips

Positioning

Don’t use display:block on inline elements to nest other elements 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 span element as a container for an absolutely position element, the absolutely positioned content can maintain its position relative to the span, 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, display:inline-block, or display:compact 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 width defined in pixels 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 margin-left: 20%; margin-right: 20%; to horizontally center content that has an undefined width in all browsers

Use text-align: center; for the container and display: inline-block; text-align: left; or just margin: 0 auto; on the element itself to horizontally center content in IE6 and IE7

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 display: table; 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 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 display: inline-block; height: 100%; for a wrapper inside the display:table-cell; vertical-align: middle standards compliant container to vertically center content that has an undefined height in IE6 and IE7

Use position: relative; text-align:right; for the container, position: absolute; for the left element, and display: inline for the right element to create bookends for a masthead without using floats

Use position: absolute; bottom: 0; as well as the following steps to create a sticky footer div at any resolution. Next create a container div that is the parent of every other div with position: relative; min-height: 100%; for standards-based browsers and height: 100% for IE6. Then set the html and body tags to height:100%. Finally, add bottom padding to the main content div to separate it from the footer. The padding may differ between IE and other browsers, so use a separate style sheet or conditional comments if necessary.

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

Use position:relative with left/right/top/bottom adjustment instead of floats for better cross browser consistency when laying out container elements

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 the 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 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 block-level element contains the inline content of each one.

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

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

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

Never float two or more columns to the same side, put each pair of left and right floated elements in a wrapper div big enough to contain both elements and padding

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 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

Only absolutely or relatively positioned elements can be animated using JavaScript

Use table-layout:fixed for data tables

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

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

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. Float elements are not acknowledged by surrounding block elements unless overflow is set to auto on the floats and the surrounding blocks.

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, you can raise the z-index on hover of the currently hovered item instead of giving each parent menu a z-index.

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 that 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.

Typography

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

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

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 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 percentages instead of px for cross browser consistency

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

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

Use text-transform 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 list-style-type:decimal in the style sheet instead of changing UL to OL in the HTML to number list items

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 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

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 issues

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

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";}

Dimensions

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

Never set width or height on the same module where borders and padding are defined. 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

Always set a width on floated elements and their child elements

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.

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 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, 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

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

Avoid 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.0 Transitional doctype 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 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

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 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.

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.

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

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 body.classname for each customizable element and define a button in JavaScript to dynamically switch classes for each applicable node once 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, content, gutter, headmargin, footmargin, sidemargin, baseline, overlay, fold, ads and widgets

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, topic, bio, ticker, alert, boilerplate, dropcap, slogan, keyword, tease, sidebar, boxscore, poll, addendum, soundbite, pullquote, plugs, followup, letterhead, dateline, byline, etc.

Use semantic class names for essay components that may need specific styling, such as objective, excerpt, aside, citation, topic, 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

Define hover, focus, and active(e.g. :link:hover, :visited:active, etc.) rules in the preceding order of operation to cascade the rules properly

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, or LessCSS for Ruby 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 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 conflicting or more specific styles that are defined after the desired rule in the CSS code by prepending the selector with references to ancestor classes or IDs

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 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 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 separate style sheet for IE 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 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

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 increase the width of a container with 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 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.

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 to 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

Make sure floated elements have a defined width

Use clear to break an element away from a floated sibling

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 to emulate newspaper column layout for articles

Place an absolutely positioned div as the last element inside a relative container and set the absolute element to height: 100%; bottom:0. Its width and left position should be the same as one of the static content div columns inside the container. Give it the border and background color you want for that content. Repeat this step for each column to create faux equal height columns using CSS. 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 and so that they will extend to the top of the page, but remember to give the header position:relative and z-index: 2 to cover up the columns.

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 an absolutely positioned div with height: 100%; and a high z-index to replace the body element and hold all the content to create a modal popup. Move it right 20px to keep it from obscuring the scrollbar in Firefox. Next, create a wrapper that will hold all the page content. Give it a width and height of 100% and overflow:auto. Use 100% height and width for the html and body elements as a base for the dimensions of the popup div. Inside the popup div, create a container with 100% width and height and a content div with undefined width and height which is always centered. For IE6, use width:100%; and right: auto for the popup. In addition, add overflow: hidden for the body tag if there is no content below the fold

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 with 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 conditional comments to create a copy of the top level link list item 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

CSS References

CSS Article Compilation

Performance Impact of CSS Selectors

Extending CSS Spriting

CSS Sprites are Stupid

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

Cascading Style Sheet Compatibility in Internet Explorer 7

CSS Enhancements in IE6

CSS Compatibility in Internet Explorer 5.5

Strategies for CSS Switching

Moving to Standards-Compliant HTML and CSS Development

CSS Code Snippets






Safari CSS Reference





Absolute and Fixed Positioning

When Links in ULs don’t work in IE
On Having Layout

How to Prevent HTML Tables from Becoming too Wide
HasLayout Triggers


Zs not Dead


Conflicting Absolute Positions
Bookend Headers

Nine Techniques for Image Replacement
What CSS did we learn in 2007

Horizontal Sizing in CSS
Vertical Sizing in CSS
Inline Elements and Padding
Padding, Borders, and Margins
Browser Archive

9 Comments »

RSS feed for comments on this post. TrackBack URI

  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: [...]


Leave a comment

You must be logged in to post a comment.

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