Tuesday, 9 September 2008

CSS: Tips from Paul Sweatte

Positioning

Only block level elements have margin and padding

Use even numbers to avoid covering 99% of the page

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

Avoid using absolute or relative positioning on main content divs

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 center block level tags horizontally

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 styles sheets or conditional comments to account for box model differences.

Use position: absolute; bottom: 0; as well as the following steps to align a footer div with the end of a page at any resolution. Next create a container div that is the parent of every other div with position: relative; min-height: 100%; height: 100%. Then set the html and body tags to height:100%. Finally, add bottom padding to the main content div and margin-bottom:-xxx (where -xxx is equal to the height of the footer) 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 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 applying margins for the static content which is greater than the width or height of the absolute content

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 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 list-style-type:none for a >ul< element, display:inline for its >li< elements, and add right side padding or 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:block for the container div and parent div plus display:inline and zoom:1 for the nested divs to create rows and columns in IE6.

Use display:-moz-inline-box; and display:inline-block; for the container divs to create grids that don’t require zoom:1 or display:table. Remember to still use display:inline for the nested divs to support IE6.

Use vertical-align:top with display:-moz-inline-box to display content consistent with the behavior of display:inline-block on other browsers

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

Use display: -moz-inline-box; -moz-box-orient:vertical; to create an inline box with vertically aligned block level child elements

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

Set display properties (text-align, vertical-align,etc)on the parent element if they do not work on the
element itself

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

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

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

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

Don’t use percentages for margins or borders

Vertical margins and text alignment only apply to block elements

The vertical-align only applies to inline and table-cell elements

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

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

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

Never use italics

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

Use percentages for all fonts to allow for browser selectable sizing

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

Use margins and the tag (or its equivalents) to control wrapping and vertical alignment of list items and headers

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

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, word-wrap: break-word; for IE, and white-space: pre-wrap for Opera and Safari to force wrapping on predefined text

Use the 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 the CSS to insert the equivalent HTML entity for Opera and Safari, which do not recognize the tag, in order to produce the effect on those browsers

Set generous bottom margins equivalent left and right margins for paragraph tags globally for create consistent and maintainable leading and 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.

Dimensions

Use ems as the measurement for container divs, and find the number of ems equal to 100% of the page width to use as your baseline

Reduce margins instead of increasing padding for cross browser consistency

Avoid negative margins on nested divs for cross browser consistency

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

Avoid padding and borders on inline text for cross browser consistency

Inline elements cannot have a defined width unless the display:block property is set

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

Box Model

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 for most content

IE6 always stretches boxes to display overflow content, while other browsers do not

IE6 doesn’t implement overflow:visible correctly

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
Background Colors and Images

Use the opacity property to create a rollover effect instead of swapping images

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 instead of image tags for images that are not content related

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

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

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

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

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

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

Add IDs for standard layout components, such as site title, site logo, breadcrumbs, navigation, sidebars, content, surveys, and edit/back/search buttons

Style fonts and colors for standard layout components first to avoid redundancy and use cascading
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
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 task

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

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

Remove all inline text and start with 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

Layout Emulation

Use multicolumn list to emulate newspaper column layout for articles

Style the corners using four or five pixel high strips before and after the main content div. These strips are created using bold tags. Each bold tag should be styled as display:block; overflow:hidden;. Surronding each set of strips should be a bold container styled as display:block; background:transparent; font-size:1px;. Each one except the last bold tag should be 1 pixel in height. Each one except the first bold tag should have the same background color as the content div. The horizontal margin for each bold tag should equal the sum of the tag’s position plus the number of remaining tags, plus one. This will produce rounded corners.

Use an alternative style sheet if no visited 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
the main page to the splash page and the rest of the page’s content was hidden.

No comments: