How to Take the Headache Out of Writing CSS
Some who are new to web design and even the seasoned veteran often have problems getting a site to display properly in every (or any for that matter) browser. Here are some simple tips to ensure your markup doesn't give you problems while trying to style it with CSS.
Parent / Child Relationships
In these tips, you'll hear me speak of parent and child elements and selectors. To explain each of these is really very simple. In your HTML markup, you have what is called a box model. The box model consists of containers, or divs, that hold content that is displayed on the page.
Each div in your markup has a relationship to the outside container which is called a parent and any containing div inside of that is referred to as the child. For example, if I have a container div that simply holds a paragraph of text the div is the parent object and the paragraph is the child object of that div.
<div id="parent"> <p class="child">Lorem Ipsum</p> </div>
Understanding CSS Selectors
This brings me to CSS selectors. Selectors are patterns; part of a CSS rule that matches a set of elements in an HTML or XML document. The declarations that appear in the block that follow the selector are applied to all elements that match this pattern, unless they’re overridden by another rule in the cascade.
A CSS selector can contain a chain of one or more simple selectors separated by combinators. A simple selector contains either an element type selector, targeting a specific element such as h1, or the universal selector targeting all elements such as *. The universal selector can be considered to be a suggestion and overridden if it isn’t the only component of the simple selector.
A simple selector can also contain class selectors such as .warning, ID selectors such as #menu, attribute selectors such as [type="submit"], and pseudo-classes such as :hover or a pseudo-element such as :first-line can also be included after the last simple selector in the chain. These selectors act like modifiers on an element type selector (or the universal selector), and qualify the selector, as if to say "but only if …"
/* Element type selector */
h1 {
color: #666;
font-weight: bold;
}
/* Universal type selector - both examples are the equivalent */
*.warning {
border:1px solid #900;
}
.warning {
border:1px solid #900;
}
/* Class selector - second example shows more specificity */
.warning {
border:1px solid #900;
}
p.warning {
border:1px solid #900;
}
/* ID selector - second example shows more specificity */
#menu {
border:1px solid #900;
}
div#menu {
border:1px solid #900;
}
/* Attribute selector */
input[type="submit"] {
border:1px solid #900;
}
/* Pseudo-class selector */
a:link {
color:red;
}
a:visited {
color:red;
}
a:focus {
color:red;
}
a:hover {
color:red;
}
a:active {
color:red;
}
/* Pseudo-element selector */
p:first-letter {
font-size:110%;
}
Using A CSS Reset
Any seasoned veteran will tell you it's best practice to clear the default browser settings before you start working to ensure optimum compatibility. Each browser has a different way of rendering elements, so you'll want to start with a clean slate. Using a CSS reset is a good way to do this, it will reduce the number of inconsistencies you will have to deal with along the way.
The goal of a reset stylesheet is to reduce browser inconsistencies in things like default line heights, margins and font sizes of headings, and so on.
Back in 2007, Eric Meyer created the CSS reset as a way of clearing up the mess of troubleshooting and as he states on his blog, "This is a starting point, not a self-contained black box of no-touchiness" so you can decide what works for you and set your own rules as to what you include in your stylesheet.
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
/* remember to define focus styles! */
:focus {
outline: 0;
}
/* remember to highlight inserts somehow! */
ins {
text-decoration: none;
}
del {
text-decoration: line-through;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
border-collapse: collapse;
border-spacing: 0;
}
Although some accessibility experts argue against removing some of these default features, this reset also removes list bullets, the blue border around linked images and the dotted outline which is an accessibility feature used for navigating the page with a keyboard, usually by hitting the tab key.
Using an HTML5 Reset
For those thinking of, or are currently using HTML5 as a DOCTYPE, I have created a reset to use that eliminates all depreciated elements and adds the proper ones needed for HTML5. You can also grab it on Snipplr here.
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,figcaption,figure,footer,header,hgroup,menu,nav,section,summary,time,mark,audio,video{margin:0;padding:0;border:0;outline:0;font-size:100%;vertical-align:baseline;background:transparent;font-weight:normal;}ol,ul,nav ul{list-style:none}blockquote,q{quotes:none}blockquote:before,blockquote:after,q:before,q:after{content:'';content:none}:focus{outline:0}ins{text-decoration:none}del{text-decoration:line-through}table{border-collapse:collapse;border-spacing:0}article,aside,canvas,details,figcaption,figure,footer,header,hgroup,menu,nav,section,summary{display:block;}input,select{vertical-align:middle;}abbr[title],dfn[title]{border-bottom:1px dotted #000;cursor:help;}hr{display:block;height:1px;border:0;border-top:1px solid #cccccc;margin:1em 0;
padding:0;}input[type='submit'],input[type='button'],input[type='text'],input[type='tel'],input[type='email'],input[type='url']{font:inherit;}button::-moz-focus-inner,input::-moz-focus-inner{border:0;}
It's Called "Cascading" for a Reason
Recently while working on a WordPress theme I purchased, I noticed that the author had defined fonts, font-sizes and just about everything else for every section or div of markup on the page. The reason it's called a Cascading Style Sheet is that you can declare a style for a parent element and it will cascade to the rest of the elements.
For instance, if I set a style for a paragraph and I want the text size to be 13px, the line-height to be 1.5em and the margin or padding on the bottom to be 20px I wouldn't set it individually for just the paragraph. I would set it for the body first and then let it cascade to the paragraph and set the margin separately.
body {
font-size:13px;
font-family: Arial, Helvetica, sans-serif;
line-height:1.5em;
}
p {
margin-bottom:20px;
}
All child elements will inherit the styles from the body declaration and there's no need to declare them separately like the example below:
body {
font-size:13px;
font-family: Arial, Helvetica, sans-serif;
line-height:1.5em;
}
p {
font-size:13px;
font-family: Arial, Helvetica, sans-serif;
line-height:1.5em;
margin-bottom:20px;
}
Write Less by Writing Shorthand
Many CSS properties can be combined into what is called "shorthand". Shorthand takes what could be many lines of CSS and shortens them into a smaller chunk that makes things easier and quicker to write. The background property is one example of many settings that can be combined. Background image, color, repeat, attachment and position are all properties that can be set and if all properties are used, you've got five lines of CSS to type out. Instead of this:
body {
background-image: url(images.jpg);
background-color: #fff;
background-repeat: no-repeat;
background-attachment:fixed;
background-position: left top;
}
You can easily do this instead:
body {
background: #fff url(images.jpg) no-repeat fixed left top;
}
Work From the Top Down
Literally start organizing your CSS from the top most elements in your HTML, as well as the top elements like body, typography and all parent containers on the page.
Declare your CSS commands on the highest level possible and once only, let the priorities cascade throughout. Only override the commands at a lower level when strictly necessary. This prevents a messy, un-organized CSS file that is difficult to maintain and understand. For example, if you have margin: 0px auto; on each and every sub div within your container - you might have trouble later on.
Organize your CSS file like a book. Start from the beginning and organize sections into chapters like body, typography, navigation and footer, indenting the child style of the top level parent. You can label or comment your sections to make them easier to find like the example below.
/*header ------------------------- */
#header-parent {style: here;}
#header-child {style: here;}
/*sidebar ------------------------ */
#sidebar-parent {style: here;}
#sidebar-child {style: here;}
/*footer ------------------------- */
#footer {style: here;}
Centering Your Layout
For those that know, it’s a simple feat. For those that don’t, finding the two necessary rules to do it right can be frustrating. In the markup, we’ll need a container to hold everything. In this container will sit the entire layout that we’d like to center on the page. I usually use a container with an id of "wrap" or "wrapper" once again indenting the child elements makes your code more organized and easy to follow.
layout goes here
Using CSS, two rules will force whatever is contained within #wrap to be centered. Giving the #wrap container a specific width (whatever size you like) helps specify the space in which the content will centered. Margin: 0px auto; is the second part that makes it all work. We’re specifying 0 pixels on top and bottom, with auto margins to the left and right.
#wrap {
width:960px;
margin: 0px auto;
}
There are a couple of points here to take note of. Do not declare the width to be 100%. This defeats the whole object since you will just have to declare the sub elements within the container and then center them using margin: 0px auto. This is bad since it means that instead of declaring the central layout once, you will have to declare it in multiple places for each element within your container.
Understanding Floats
Floats are a way to horizontally position elements next to each other without removing or changing their position in the flow of the document. They do however affect the surrounding elements in the flow and require to be "cleared" at the end of the floated element or the containing parent element.

An example of floated elements
There are four valid values for the float property. The left and right values float elements those directions respectively. The default none ensures the element will not float and inherit which will assume the float value from that elements parent element.
Clearing a float basically specifies that any element below the floated element(s) will be forced to appear outside of the float itself. So if you have two floated elements in a div like the image above, any markup or elements below will also try to float instead of appearing in it's specified position.

Example of uncleared float from left-container above
In the above example, the sidebar has float:right applied to it and is shorter than the main content area. The footer then will jump up into that available space as is required by the float. To fix the problem, the footer can be cleared to ensure it stays beneath both floated columns.

Example of a cleared float
There are also four valid values for the clear property as well. The most commonly used value both, clears floats coming from either direction. The left and right values can be used to only clear the float from one direction respectively. Default is none, which is basically unnecessary unless you are removing a clear value from a cascade. Inherit can also be used, but of course not supported in Internet Explorer.
Float Clearing Techniques
If you know what the element after your float is going to be you can simply apply clear:both; to that element and be done with it. Unfortunately, it doesn't always work that way. Here are some other ways to successfully clear a float.
The Empty Div Method
The empty div method is literally, an empty div with an inline style applied to it or given a class of "clear". <div style="clear: both;"></div> or <div class="clear"></div>. Sometimes a <br /> element or some other random element is used, but the div is the most common because it has no browser default styling, doesn’t have any special function, and is unlikely to be generically styled with CSS. This method is not semantic and does add additional markup, it simply is there for presentation.
The Overflow Method
The overflow method relies on setting the overflow CSS property on a parent element. If this property is set to auto or hidden on the parent element, the parent will expand to contain the floats, clearing it for succeeding elements. This method tends to be semantic as it does not require any additional elements. However if you do add a new div just to apply this, it is also not semantic just as the empty div method. Keep in mind that the overflow property isn’t specifically for clearing floats. Be careful as you may hide content or get those unwanted scroll bars.
The Clearfix Method
The clearfix method uses a clever CSS pseudo selector :after to clear floats. Rather than setting the overflow on the parent, you apply an additional class like “clearfix” to it. This will apply a small bit of content, hidden from view, after the parent element which clears the float. This method of course causes problems with older browsers, as additional code needs to be used.
.clearfix:after {
content: ".";
visibility: hidden;
display: block;
height: 0;
clear: both;
}
Float Problems, Bugs and Fixes
When working with floating elements you are going to come across some issues. Below are some of the most common problems and how to fix them without pulling your hair out.
Parent Element Collapse
Floating elements can affect the parent element they are contained in. When a parent element contains nothing but floated elements, it will collapse to a height of 0 pixels. It's not apparent if the item doesn't have a visual background or border, but it's something you should definitely be aware of.

Example of a collapsed parent element
The easiest way to deal with the collapse issue is by clearing the float after the floated elements in the parent container but before the close of the container or simply applying float:left; to the parent element also.
Pushdown
Pushdown is a symptom of an element, typically an image, inside a floated item that is wider than the float itself. Most browsers will render the image outside the float, but not have the part sticking out affect other layout. Internet Explorer of course will expand the float to contain the image or element, often breaking the layout.

Example of pushdown from content being to wide
The easiest way to fix the pushdown issue is to apply overflow:hidden; to the parent element and this will hide any excess that would usually hang out of the element.
Double Margin Bug
Another unfortunate thing about dealing with Internet Explorer 6 is that if you apply a margin in the same direction as the float, it will double the margin. The easiest way to fix this issue is to set display:inline; on the floated element.
The 3 Pixel Jog
When text is placed next to a floated element it is wondrously moved away by 3px like the floated element has a forcefield around it. The easiest way to fix this issue to set a width or height on the text element.
Bottom Margin Bug
When a floated parent element has floated children inside of it, the bottom margin on those children will be ignored by the parent. The easiest way to fix this issue is by using padding-bottom on the parent element.
Understanding Css Positioning
There are four other states of positioning beyond floating that are used quite widely: static, relative, absolute and fixed.
Static Positioning
Static is the default position for any element on a page. If no position is defined, it will be static and will display based on where it is in the HTML document and how it displays inside the normal document flow. If you apply top or left rules to an element that has a static position, those rules will be ignored.
Relative Positioning
Relative positioning gives you the control to absolutely position children elements inside of it. Instead of basing the position of the element upon the browser view port like absolute (which we'll get to next), it starts from where the element would be if it were still in the normal flow.
Absolute Positioning
Absolute tells the browser to remove the object from the normal flow of the document and place it in an exact location on the page unless contained in a parent element with the position:relative; property. It is also taken out of the normal flow of the document - it won't affect how the elements before it or after it in the HTML are positioned on the page. Absolute positioning uses four properties that specify where to locate it in proportion to the parent relative element or in proportion to the page if the parent does not have position:relative; specified. The four properties are shown in use as follows:
#yourdiv {
position:absolute;
top:0px;
left:45px;
}
This would give the #yourdiv element a position of 5px from the top of the browser window, 35px from the left and the rest would be default.
Fixed Positioning
Fixed positioning is a lot like absolute positioning. The position of the element is calculated in the same way as absolute, from the sides of the view port. Fixed elements are fixed in that specified location, like a watermark. Everything else on the page will then scroll past that element. For example if you set a background image with a fixed property, the content will scroll and the background image will stay "fixed" in it's normal position.
Comment, Comment, Comment
Unfortunately, you are not writing your CSS code just for yourself, some day some poor sap will have to debug it. Always make numerous comments inside your CSS file to explain why you are doing things in a specific way.
/* This is a CSS comment ------------------------------- */
#header {
property:definition;
}
Using a CSS Cheatsheet
I've always found that it helps to have a reference cheatsheet available when you just can't remember what property does or doesn't do while writing CSS. There are many of them out there, so print one off and keep it handy.

CSS3 cheatsheet from veign.com
- http://www.veign.com/reference/css3-guide.php
- http://lesliefranke.com/files/reference/csscheatsheet.html
- http://www.smashingmagazine.com/2009/07/13/css-3-cheat-sheet-pdf/
- http://www.addedbytes.com/cheat-sheets/css-cheat-sheet/
Use Firebug to Troubleshoot Live in Your Browser
Someday you might find yourself having to fix someone else's CSS more often than you think (or even your own, for that matter). Use the Firebug add-on for Firefox or Google Chrome to debug your CSS. This is a life-saver with regards to giving you an insight into exactly where your design might be broken and why.
Get Primitive With Internet Explorer
Let's say your design works perfectly in Firefox, but is broken in Internet Explorer. You can't exactly use Firebug to determine where the problem might be since it only works with Firefox and Chrome, so how do you debug an IE6 or IE7 stylesheet? Simply add border:1 px solid red; to the problematic elements. This way you can often see why certain elements do not fit into the space available. It is a bit primitive and simple, but it works!
Understanding CSS and knowing how to use it the right way can definitely save you many troubles along the way. If you follow these tips and develop a method for writing your CSS from the start it ensures less problems along the way and now that you know how to fix some of them, it should make the process a little easier so you're not pulling your hair out or cursing the name of Internet Explorer.

-
http://mrturtle.com Luke Hartman
-
http://www.vagrantradio.com Jason Pant
-
http://cdnpic.com cdnpic
-
http://www.vagrantradio.com VagrantRadio














