Formatting:
All CSS
documents must use two spaces for indentation and files should have no trailing
whitespace. Other formatting rules:
- Use
soft-tabs with a two space indent.
- Use
double quotes.
- Use
shorthand notation where possible.
- Put
spaces after: in property declarations.
- Put
spaces before {in rule declarations.
- Use
hex colour codes #000 unless using rgba ().
- Always
provide fall-back properties for older browsers.
- Use
one line per property declaration.
- Always
follow a rule with one line of whitespace.
- Always
quote URL () and @import () contents.
- Do
not indent blocks.
For
example:
|
.media
{
overflow:
hidden;
color:
#fff;
background-color:
#000; /* Fall-back value */
background-image:
linear-gradient (black, grey);
}
.media
.img {
float:
left;
border:
1px solid #ccc;
}
.media
.img img {
display:
block;
}
.media
.content {
background:
#fff url (".../images/media-background.png") no-repeat;
}
|
Naming:
All ids,
classes and attributes must be lowercase with hyphens used for separation.
For
example
|
/* GOOD
*/
.dataset-list
{}
/* BAD
*/
.datasetlist
{}
.datasetList
{}
.dataset_list
{}
|
Comments:
Comments
should be used liberally to explain anything that may be unclear at first
glance, especially IE workarounds or hacks.
For
example
|
.prose
p {
font-size:
1.1666em /* 14px / 12px */;
}
.ie7
.search-form {
/*
Force the item to have layout in IE7 by setting display to block.
See:
http://reference.sitepoint.com/css/haslayout */
display:
inline-block;
}
|
Modularity & Specificity:
Try keep
all selectors loosely grouped into modules where possible and avoid having too
many selectors in one declaration to make them easy to override.
For
example
|
/*
Avoid */
ul#dataset-list
{}
ul#dataset-list
li {}
ul#dataset-list
li p a.download {}
|
Instead
here we would create a dataset module and styling the item outside of the
container allows you to use it on its own example on a dataset page:
For
example
|
.dataset-list
{}
.dataset-list-item
{}
.dataset-list-item
.download {}
|
In the
same vein use classes make the styles more robust, especially where the HTML
may change. For example when styling social links:
For
example
|
<ul
class="social">
<li><a
href="">Twitter</a></li>
<li><a
href="">Facebook</a></li>
<li><a
href="">LinkedIn</a></li>
</ul>
|
You may
use pseudo selectors to keep the HTML clean:
For
example
|
.social
li: nth-child (1) a {
background-image:
url (twitter.png);
}
.social
li: nth-child (2) a {
background-image:
url (facebook.png);
}
.social
li: nth-child (3) a {
background-image:
url (linked-in.png);
}
|
However
this will break any time the HTML changes for example if an item is added or
removed. Instead we can use class names to ensure the icons always match the
elements (Also you’d probably sprite the image :
For
Example
|
.social
.twitter {
background-image:
url (twitter.png);
}
.social
.Facebook {
background-image:
url (facebook.png);
}
.social
.linked-in {
background-image:
url (linked-in.png);
}
|
Avoid
using tag names in selectors as this prevents re-use in other contexts.
For
Example
|
/*
Cannot use this class on an <ol> or <div> element */
ul.dataset-item
{}
|
Also ids
should not be used in selectors as it makes it far too difficult to override
later in the cascade.
For
Example
|
/*
Cannot override this button style without including an id */
.btn#download
{}
|
Make it Readable:
The
readability of your CSS is incredibly important, though most people
overlook why it’s important. Great readability of your CSS makes it
much easier to maintain in the future, as you’ll be able to find elements
quicker. Also, you’ll never know who might need to look at your code later on. <editors-note> when
writing CSS, most developers fall into one of two groups.
Keep it Consistent:
Along the
lines of keeping your code readable is making sure that the CSS is consistent.
You should start to develop your own “sub-language” of CSS that allows you to
quickly name things. There are certain classes that I create in nearly every
theme, and I use the same name each time. For example, I use “.caption-right”
to float images which contain a caption to the right.
Think about things like whether or not you’ll use
underscores or dashes in your ID’s and class names, and in what cases you’ll
use them. When you start creating your own standards for CSS, you’ll become
much more proficient.
Start with a Framework:
Some
design purists scoff at the thought of using a CSS framework with
each design, but I believe that if someone else has taken the time to maintain
a tool that speeds up production, why reinvent the wheel? I know frameworks
shouldn’t be used in every instance, but most of the time they can help.
Many designers have their own framework that they
have created over time, and that’s a great idea too. It helps keep consistency
within the projects.
Use a Reset:
Most CSS
frameworks have a reset built-in, but if you’re not going to use one
then at least consider using a reset. Resets essentially eliminate
browser inconsistencies such as heights, font sizes, margins, headings, etc.
The reset allows your layout look consistent in all browsers.
The Meyer Web is
a popular reset, along with Yahoo’s
developer reset. Or you could always roll your own
reset, if that tickles your fancy.
Organize the Style sheet with a Top-down Structure:
It always
makes sense to lay your style sheet out in a way that allows you to quickly
find parts of your code. I recommend a top-down format that tackles styles as
they appear in the source code. So, an example style sheet might be ordered
like this:
1. Generic
classes (body, a, p, h1, etc.)
2. #header
3. #nav-menu
4. #main-content
Combine Elements:
Elements in a style sheet sometimes share
properties. Instead of re-writing previous code, why not just combine them? For
example, your h1, h2, and h3 elements might all share the same font and color:
1.
h1, h2, h3 {font-family: Tahoma, color: #333}
We could
add unique characteristics to each of these header styles if we wanted (i.e. h1
{size: 2.1em}) later in the style sheet.
Create Your HTML First:
Many
designers create their CSS at the same time they create the HTML. It seems
logical to create both at the same time, but actually you’ll save even more
time if you create the entire HTML mock-up first. The reasoning
behind this method is that you know all the elements of your site layout, but
you don’t know what CSS you’ll need with your design. Creating the HTML layout
first allows you to visualize the entire page as a whole, and allows you to
think of your CSS in a more holistic, top-down manner.
Use Multiple Classes:
Sometimes
it’s beneficial to add multiple classes to an element. Let’s say that you have
a <div> “box” that you want to float right, and you’ve already got a
class .right in your CSS that floats everything to the right. You can simply
add an extra class in the declaration, like so:
<div class="box right"></div>
You can add as many classes as you’d like
(space separated) to any declaration. <editors-note> be
very careful when using ids and class-names like “left” and “right.” I will use
them, but only for things such as blog posts. How come? Let’s imagine that,
down the road, you decide that you’d rather see the box floated to the LEFT. In
this case, you’d have to return to your HTML and change the class-name – all in
order to adjust the presentation of the page. This is un-semantic.
Remember – HTML is for mark-up and content. CSS is for presentation. If
you must return to your HTML to change the presentation (or styling) of the
page, you’re doing it wrong!
</editors-note>
Use the Right Doctype:
The
doctype declaration matters a whole lot on whether or not your mark-up and CSS
will validate. In fact, the entire look and feel of your site can change
greatly depending on the DOCTYPE that you declare.
Learn
more about which DOCTYPE to use at A List Apart.
<editors-note>
I use
HTML5′s doctype for all of my projects.
1.
<!DOCTYPE html>
“What’s nice about this new DOCTYPE, especially, is
that all current browsers (IE, FF, Opera, and Safari) will look at it and
switch the content into standards mode – even though they don’t implement
HTML5. This means that you could start writing your web pages using HTML5 today
and have them last for a very, very, long time.”
</editors-note>
Use Shorthand:
You can
shrink your code considerably by using shorthand when crafting your CSS. For
elements like padding, margin, font and some others, you can combine styles in
one line. For example, a div might have these styles:
1.
#crayon {
2.
margin-left: 5px;
3.
margin-right: 7px;
4.
margin-top: 8px;
5.
}
You could
combine those styles in one line, like so:
1.
#crayon {
2.
margin: 8px 7px 0px 5px; // top, rightright, bottombottom, and left values, respectively.
3.
}
If you
need more help, here’s a comprehensive
guide on CSS shorthand properties.
Comment your CSS:
Just like
any other language, it’s a great idea to comment your code in sections. To add
a comment, simply add /* behind the comment, and */ to close it, like so
1.
/* Here's how you comment CSS */
Understand the Difference Between Blocks vs. Inline Elements:
Block
elements are elements that naturally clear each line after they’re declared,
spanning the whole width of the available space. Inline elements take only as
much space as they need, and don’t force a new line after they’re used.
Here are
the lists of elements that are either inline or block:
1.
span, a, strong, img, br, input, abbr, acronym
And the
block elements:
1.
div, h1...h6, p, ul, li, table, block
quote, pre, form
Alphabetize your Properties:
While
this is more of a frivolous tip, it can come in handy for quick scanning.
1.
#cotton-candy {
2.
color: #fff;
3.
float: left;
4.
font-weight:
5.
height: 200px;
6.
margin: 0;
7.
padding: 0;
8.
width: 150px;
9.
}
<editors-note> Ehh…
sacrifice speed for slightly improved readability? I’d pass – but decide for
yourself! </editors-note>
Use CSS Compressors:
CSS
compressors help shrink CSS file size by removing line breaks, white spaces,
and combining elements. This combination can greatly reduce the file size,
which speeds up browser loading. CSS Optimizer and CSS Compressor are two excellent
online tools that can shrink CSS. It should be noted that shrinking your CSS
can provide gains in performance, but you lose some of the readability of your
CSS.
Make Use of Generic Classes:
You’ll
find that there are certain styles that you’re applying over and over. Instead
of adding that particular style to each ID, you can create generic classes and
add them to the IDs or other CSS classes (using tip #8).
For example, I find myself using float: right and
float: left over and over in my designs. So I simply add the classes .left and
.right to my style sheet, and reference it in the elements.
1.
.left {float: left}
2.
.right right {float:rightright}
3.
4.
<div id="coolbox" class="left">...</div>
This way you don’t have to constantly add “float:
left” to all the elements that need to be floated.
<editors-note> Please
refer to editor’s notes for #8. </editors-note>
Use “Margin: 0 auto” to centre Layouts:
Many
beginners to CSS can’t figure out why you can’t simply use float:
center to achieve that centred effect on block-level elements. If only it
were that easy! Unfortunately, you’ll need to use
1.
margin: 0 auto; // top, bottombottom - and left, rightright values, respectively.
to center divs, paragraphs or other elements in
your layout.
<editors-note> By
declaring that both the left AND the right margins of an element must be
identical, they have no choice but to center the element within its containing
element. </editors-note>
Don’t Just Wrap a DIV Around It:
When
starting out, there’s a temptation to wrap a div with an ID or class around an
element and create a style for it.
1.
<div class="header-text"><h1>Header Text</h1></div>
Sometimes it might seem easier to just create
unique element styles like the above example, but you’ll start to clutter your
style sheet. This would have worked just fine:
1.
<h1>Header Text</h1>
Then you
can easily add a style to the h1 instead of a parent div.
Use Firebug:
If you
haven’t downloaded Firebug yet,
stop and go do it. Seriously. This little tool is a must have for any
web developer. Among the many features that come bundled with the Firefox
extension (debug JavaScript, inspect HTML, find errors), you can also visually
inspect, modify, and edit CSS in real-time. You can learn more about what
Firebug does on the official Firebug
website.
Hack Less:
Avoid
using as little browser-specific hacks if at all possible. There is a
tremendous pressure to make sure that designs look consistent across all
browsers, but using hacks only makes your designs harder to maintain in the
future. Plus, using a reset file can eliminate nearly all of the rendering
irregularities between browsers.
Use Absolute Positioning Sparingly:
Absolute
positioning is a handy aspect of CSS that allows you to define
where exactly an element should be positioned on a page to the exact
pixel. However, because of absolute positioning disregard for other elements on
the page, the layouts can get quite hairy if there are multiple absolutely
positioned elements running around the layout.
Use Text-transform:
Text-transform is
a highly-useful CSS property that allows you to “standardize” how text is
formatted on your site. For example, say you want to create some headers that
only have lowercase letters. Just add the text-transform property to the header
style like so:
1.
text-transform: lowercase;
Now all of the letters in the header will be
lowercase by default. Text-transform allows you to modify your text (first letter
capitalized, all letters capitalized, or all lowercase) with a simple property.
Don’t use Negative Margins to Hide your h1:
Oftentimes
people will use an image for their header text, and then either use display:
none or a negative margin to float the h1 off the page. Matt Cutts, the head of Google’s Web-spam
team, has officially said that this is a bad idea, as Google might think it’s
spam.
As Mr Cutts explicitly says, avoid hiding your
logo’s text with CSS. Just use the alt tag. While many claim that you can still
use CSS to hide an h1 tag as long as the h1 is the same as the logo text, I
prefer to err on the safe side.
Validate Your CSS and XHTML:
Validating
your CSS and XHTML does more than give a sense of pride: it helps you quickly
spot errors in your code. If you’re working on a design and for some reason
things just aren’t looking right, try running the mark-up and CSS validator and see
what errors pop up. Usually you’ll find that you forgot to close a div
somewhere, or a missed semi-colon in a CSS property.
Ems vs. Pixels:
There’s
always been a strong debate as to whether it’s better to use pixels (px) or ems
(em) when defining font sizes. Pixels are a more static way to define font
sizes, and ems are more scalable with different browser sizes and mobile
devices. With the advent of many different types of web browsing (laptop,
mobile, etc.), ems are increasingly becoming the default for font size
measurements as they allow the greatest form of flexibility. You can read more
about why you should use ems for font sizes in this
thoughtful forum thread. About.com also has a great article on
the differences
between the measurement sizes.
<editors-note>Don’t take me to the farm on
this one – but I’d be willing to bet that, thanks to browser zooming, the
majority of designers are defaulting to pixel based layouts. What do you
think? </editors-note>
Don’t Underestimate the List
Lists are
a great way to present data in a structured format that’s easy to modify the
style. Thanks to the display property, you don’t have to just use the list as a
text attribute. Lists are also great for creating navigation menus and things
of the sort.
Many beginners use div’s to make each element in
the list because they don’t understand how to properly utilize them. It’s well
worth the effort to use brush up on learning list elements to structure data in
the future.
<editors-note>
You’ll
often see navigation links like so:
1.
<a href="http://net.tutsplus.com/tutorials/html-css-techniques/30-css-best-practices-for-beginners/#">Home</a>
2.
<a href="http://net.tutsplus.com/tutorials/html-css-techniques/30-css-best-practices-for-beginners/#">About</a>
3.
<a href="http://net.tutsplus.com/tutorials/html-css-techniques/30-css-best-practices-for-beginners/#">Services</a>
4.
<a href="http://net.tutsplus.com/tutorials/html-css-techniques/30-css-best-practices-for-beginners/#">Contact</a>
Though, technically, this will work just fine after
a bit of CSS, it’s sloppy. If you’re adding a list of links, use an unordered
list, silly goose!
</editors-note>
Avoid Extra Selectors:
It’s easy
to unknowingly add extra selectors to our CSS that clutters the style sheet.
One common example of adding extra selectors is with lists.
1.
body #container .someclass ul li {....}
In this
instance, just the .someclass li would have worked just fine.
1.
.someclass li {...}
Adding extra selectors won’t bring Armageddon or
anything of the sort, but they do keep your CSS from being as simple and clean
as possible.
Add Margins and Padding to All:
Different
browsers render elements differently. IE renders certain elements differently
than Firefox. IE 6 renders elements differently than IE 7 and IE 8. While the
browsers are starting to adhere more closely toW3C standards,
they’re still not perfect (*cough IE cough*).
One of the main differences between versions of
browsers is how padding and margins are rendered. If you’re not already using a
reset, you might want to define the margin and padding for all elements on the
page, to be on the safe side. You can do this quickly with a global reset, like
so:
1.
* {margin: 0; padding: 0;}
Now all elements have a padding and
margin of 0, unless defined by another style in the style sheet.
<editors-note> the problem is that,
because EVERYTHING is zeroed out with this method, you’ll potentially cause
yourself more harm than help. Are you sure that you want every single element’s
margins and padding zeroed? If so – that’s perfectly acceptable. But at least
consider it. </editors-note>
When Ready, Try Object Oriented CSS
Object
Oriented programming is the separation of elements in the code so that they’re
easier to maintain reuse. Object Oriented CSS follows
the same principle of separating different aspects of the style sheet(s) into
more logical sections, making your CSS more modular and reusable.
Here’s is a slide presentation of how Object
Oriented CSS works:
From Nicole
Sullivan.
If you’re new to the CSS/XHTML game, OOCSS might be
a bit of a challenge in the beginning. But the principles are great to
understand for object oriented programming in general.
Use Multiple Style-sheets:
Depending
on the complexity of the design and the size of the site, it’s sometimes easier
to make smaller, multiple style sheets instead of one giant style sheet. Aside
from it being easier for the designer to manage, multiple style sheets allow
you to leave out CSS on certain pages that don’t need them.
For example, I might have a polling program that
would have a unique set of styles. Instead of including the poll styles to the
main style sheet, I could just create a poll.css and the style sheet
only to the pages that show the poll.
<editors-note> However, be sure to
consider the number of HTTP requests that are being made. Many designers prefer
to develop with multiple style sheets, and then combine them into one file.
This reduces the number of HTTP requests to one. Also, the entire file will be
cached on the user’s computer. </editors-note>
Check for Closed Elements First When Debugging:
If you’re
noticing that your design looks a tad wonky, there’s a good chance it’s because
you’ve left off a closing </div>. You can use the XHTML validator to help sniff out all
sorts of errors too.
- Formatting
All
CSS documents must use two spaces for indentation and files should
have no trailing whitespace. Other formatting rules:
- Use soft-tabs with a two space indent.
- Use double quotes.
- Use shorthand notation where possible.
- Put spaces after: in property declarations.
- Put spaces before {in rule declarations.
- Use hex colour codes #000 unless using rgba ().
- Always provide fall-back properties for older browsers.
- Use one line per property declaration.
- Always follow a rule with one line of whitespace.
- Always quote URL () and @import () contents.
- Do not indent blocks.
For
example:
|
.media
{
overflow:
hidden;
color:
#fff;
background-color:
#000; /* Fall-back value */
background-image:
linear-gradient (black, grey);
}
.media
.img {
float:
left;
border:
1px solid #ccc;
}
.media
.img img {
display:
block;
}
.media
.content {
background:
#fff url (".../images/media-background.png") no-repeat;
}
|
- Naming
All
ids, classes and attributes must be lowercase with hyphens used for
separation.
For
example
|
/*
GOOD */
.dataset-list
{}
/*
BAD */
.datasetlist
{}
.datasetList
{}
.dataset_list
{}
|
- Comments
Comments
should be used liberally to explain anything that may be unclear at
first glance, especially IE workarounds or hacks.
For
example
|
.prose
p {
font-size:
1.1666em /* 14px / 12px */;
}
.ie7
.search-form {
/*
Force the item to have layout in IE7 by setting display to block.
See:
http://reference.sitepoint.com/css/haslayout */
display:
inline-block;
}
|
- Modularity & Specificity
Try
keep all selectors loosely grouped into modules where possible and
avoid having too many selectors in one declaration to make them easy
to override.
For
example
|
/*
Avoid */
ul#dataset-list
{}
ul#dataset-list
li {}
ul#dataset-list
li p a.download {}
|
Instead
here we would create a dataset module and styling the item outside of
the container allows you to use it on its own example on a dataset
page:
For
example
|
.dataset-list
{}
.dataset-list-item
{}
.dataset-list-item
.download {}
|
In
the same vein use classes make the styles more robust, especially
where the HTML may change. For example when styling social links:
For
example
|
<ul
class="social">
<li><a
href="">Twitter</a></li>
<li><a
href="">Facebook</a></li>
<li><a
href="">LinkedIn</a></li>
</ul>
|
You
may use pseudo selectors to keep the HTML clean:
For
example
|
.social
li: nth-child (1) a {
background-image:
url (twitter.png);
}
.social
li: nth-child (2) a {
background-image:
url (facebook.png);
}
.social
li: nth-child (3) a {
background-image:
url (linked-in.png);
}
|
However
this will break any time the HTML changes for example if an item is
added or removed. Instead we can use class names to ensure the icons
always match the elements (Also you’d probably sprite the image :
For
Example
|
.social
.twitter {
background-image:
url (twitter.png);
}
.social
.Facebook {
background-image:
url (facebook.png);
}
.social
.linked-in {
background-image:
url (linked-in.png);
}
|
Avoid
using tag names in selectors as this prevents re-use in other
contexts.
For
Example
|
/*
Cannot use this class on an <ol> or <div> element */
ul.dataset-item
{}
|
Also
ids should not be used in selectors as it makes it far too difficult
to override later in the cascade.
For
Example
|
/*
Cannot override this button style without including an id */
.btn#download
{}
|
- Make it Readable
The
readability of your CSS is incredibly important, though most people
overlook why it’s
important. Great readability of your CSS makes it much easier to
maintain in the future, as you’ll be able to find elements quicker.
Also, you’ll never know who might need to look at your code later
on. <editors-note> when
writing CSS, most developers fall into one of two groups.
- Keep it Consistent
Along
the lines of keeping your code readable is making sure that the CSS
is consistent. You should start to develop your own “sub-language”
of CSS that allows you to quickly name things. There are certain
classes that I create in nearly every theme, and I use the same name
each time. For example, I use “.caption-right” to float images
which contain a caption to the right.
Think about things
like whether or not you’ll use underscores or dashes in your ID’s
and class names, and in what cases you’ll use them. When you start
creating your own standards for CSS, you’ll become much more
proficient.
- Start with a Framework
Some
design purists scoff at the thought of using a CSS
framework with each design, but I believe that if someone
else has taken the time to maintain a tool that speeds up production,
why reinvent the wheel? I know frameworks shouldn’t be used in
every instance, but most of the time they can help.
Many designers have
their own framework that they have created over time, and that’s a
great idea too. It helps keep consistency within the projects.
- Use a Reset
Most
CSS frameworks have a reset built-in, but if you’re not going to
use one then at
least consider
using a reset. Resets essentially eliminate browser inconsistencies
such as heights, font sizes, margins, headings, etc. The reset allows
your layout look consistent in all browsers.
The Meyer
Web is a popular reset, along with Yahoo’s
developer reset. Or you could always roll
your own reset, if that tickles your fancy.
- Organize the Style sheet with a Top-down Structure
It always makes
sense to lay your style sheet out in a way that allows you to quickly
find parts of your code. I recommend a top-down format that tackles
styles as they appear in the source code. So, an example style sheet
might be ordered like this:
- Generic classes (body, a, p, h1, etc.)
- #header
- #nav-menu
- #main-content
.
Combine Elements
Elements in a style
sheet sometimes share properties. Instead of re-writing previous
code, why not just combine them? For example, your h1, h2, and h3
elements might all share the same font and color:
- h1, h2, h3 {font-family: Tahoma, color: #333}
We
could add unique characteristics to each of these header styles if we
wanted (i.e. h1 {size: 2.1em}) later in the style sheet.
- Create Your HTML First
Many designers
create their CSS at the same time they create the HTML. It seems
logical to create both at the same time, but actually you’ll save
even more time if you create the entire HTML
mock-up first. The reasoning behind this method is that you know all
the elements of your site layout, but you don’t know what CSS
you’ll need with your design. Creating the HTML layout first allows
you to visualize the entire page as a whole, and allows you to think
of your CSS in a more holistic, top-down manner.
- Use Multiple Classes
Sometimes
it’s beneficial to add multiple classes to an element. Let’s say
that you have a <div> “box” that you want to float right,
and you’ve already got a class .right in your CSS that floats
everything to the right. You can simply add an extra class in the
declaration, like so:
<div class="box right"></div>
You can add as many
classes as you’d like (space separated)
to any declaration. <editors-note> be
very careful when using ids and class-names like “left” and
“right.” I will use them, but only for things such as blog posts.
How come? Let’s imagine that, down the road, you decide that you’d
rather see the box floated to the LEFT. In this case, you’d have to
return to your HTML and change the class-name – all in order to
adjust the presentation of
the page. This is un-semantic. Remember – HTML is for mark-up and
content. CSS is for presentation. If
you must return to your HTML to change the presentation (or styling)
of the page, you’re doing it wrong!
</editors-note>
- Use the Right Doctype
The
doctype declaration matters a whole lot on whether or not your
mark-up and CSS will validate. In fact, the entire look and feel of
your site can change greatly depending on the DOCTYPE that you
declare.
Learn
more about which DOCTYPE to use at A
List Apart.
<editors-note>
I use HTML5′s
doctype for all of my projects.
- <!DOCTYPE html>
“What’s nice
about this new DOCTYPE, especially, is that all current browsers (IE,
FF, Opera, and Safari) will look at it and switch the content into
standards mode – even though they don’t implement HTML5. This
means that you could start writing your web pages using HTML5 today
and have them last for a very, very, long time.”
</editors-note>
- Use Shorthand
You
can shrink your code considerably by using shorthand when crafting
your CSS. For elements like padding, margin, font and some others,
you can combine styles in one line. For example, a div might have
these styles:
- #crayon {
- margin-left: 5px;
- margin-right: 7px;
- margin-top: 8px;
- }
You
could combine those styles in one line, like so:
- #crayon {
- margin: 8px 7px 0px 5px; // top, rightright, bottombottom, and left values, respectively.
- }
If
you need more help, here’s a comprehensive
guide on CSS shorthand properties.
- Comment your CSS
Just
like any other language, it’s a great idea to comment your code in
sections. To add a comment, simply add /* behind the comment, and */
to close it, like so
- /* Here's how you comment CSS */
- Understand the Difference Between Blocks vs. Inline Elements
Block
elements are elements that naturally clear each line after they’re
declared, spanning the whole width of the available space. Inline
elements take only as much space as they need, and don’t force a
new line after they’re used.
Here
are the lists of elements that are either inline or block:
- span, a, strong, img, br, input, abbr, acronym
And the block
elements:
- div, h1...h6, p, ul, li, table, block quote, pre, form
- Alphabetize your Properties
While
this is more of a frivolous tip, it can come in handy for quick
scanning.
- #cotton-candy {
- color: #fff;
- float: left;
- font-weight:
- height: 200px;
- margin: 0;
- padding: 0;
- width: 150px;
- }
<editors-note> Ehh…
sacrifice speed for slightly improved readability? I’d pass – but
decide for yourself!
</editors-note>
- Use CSS Compressors
CSS
compressors help shrink CSS file size by removing line breaks, white
spaces, and combining elements. This combination can greatly reduce
the file size, which speeds up browser loading. CSS
Optimizer and CSS
Compressor are two excellent online tools that can shrink
CSS. It should be noted that shrinking your CSS can provide gains in
performance, but you lose some of the readability of your CSS.
- Make Use of Generic Classes
You’ll
find that there are certain styles that you’re applying over and
over. Instead of adding that particular style to each ID, you can
create generic classes and add them to the IDs or other CSS classes
(using tip #8).
For example, I find
myself using float: right and float: left over and over in my
designs. So I simply add the classes .left and .right to my style
sheet, and reference it in the elements.
- .left {float: left}
- .right right {float:rightright}
- <div id="coolbox" class="left">...</div>
This way you don’t
have to constantly add “float: left” to all the elements that
need to be floated.
<editors-note> Please
refer to editor’s notes for #8. </editors-note>
- Use “Margin: 0 auto” to Center Layouts
Many
beginners to CSS can’t figure out why you can’t simply use float:
center to
achieve that centred effect on block-level elements. If only it were
that easy! Unfortunately, you’ll need to use
- margin: 0 auto; // top, bottombottom - and left, rightright values, respectively.
to center divs,
paragraphs or other elements in your layout.
<editors-note> By
declaring that both the left AND the right margins of an element must
be identical, they have no choice but to center the element within
its containing element. </editors-note>
- Don’t Just Wrap a DIV Around It
When
starting out, there’s a temptation to wrap a div with an ID or
class around an element and create a style for it.
- <div class="header-text"><h1>Header Text</h1></div>
Sometimes it might
seem easier to just create unique element styles like the above
example, but you’ll start to clutter your style sheet. This would
have worked just fine:
- <h1>Header Text</h1>
Then
you can easily add a style to the h1 instead of a parent div.
- Use Firebug
If
you haven’t downloaded Firebug yet,
stop and go do it. Seriously. This little tool is a must
have for
any web developer. Among the many features that come bundled with the
Firefox extension (debug JavaScript, inspect HTML, find errors), you
can also visually inspect, modify, and edit CSS in real-time. You can
learn more about what Firebug does on the official Firebug
website.
- Hack Less
Avoid
using as little browser-specific hacks if at all possible. There is a
tremendous pressure to make sure that designs look consistent across
all browsers, but using hacks only makes your designs harder to
maintain in the future. Plus, using a reset file can eliminate nearly
all of the rendering irregularities between browsers.
- Use Absolute Positioning Sparingly
Absolute
positioning is a handy aspect of CSS that allows you to
define where exactly an
element should be positioned on a page to the exact pixel. However,
because of absolute positioning’s disregard for other elements on
the page, the layouts can get quite hairy if there are multiple
absolutely positioned elements running around the layout.
- Use Text-transform
Text-transform is
a highly-useful CSS property that allows you to “standardize” how
text is formatted on your site. For example, say you want to create
some headers that only have lowercase letters. Just add the
text-transform property to the header style like so:
- text-transform: lowercase;
Now all of the
letters in the header will be lowercase by default. Text-transform
allows you to modify your text (first letter capitalized, all letters
capitalized, or all lowercase) with a simple property.
- Don’t use Negative Margins to Hide Your h1
Oftentimes
people will use an image for their header text, and then either use
display: none or a negative margin to float the h1 off the page. Matt
Cutts, the head of Google’s Web-spam team, has officially said
that this is a bad idea, as Google might think it’s spam.
As Mr Cutts
explicitly says, avoid hiding your logo’s text with CSS. Just use
the alt tag. While many claim that you can still use CSS to hide an
h1 tag as long as the h1 is the same as the logo text, I prefer to
err on the safe side.
- Validate Your CSS and XHTML
Validating
your CSS and XHTML does more than give a sense of pride: it helps you
quickly spot errors in your code. If you’re working on a design and
for some reason things just aren’t looking right, try running the
mark-up and CSS
validator and see what errors pop up. Usually you’ll find
that you forgot to close a div somewhere, or a missed semi-colon in a
CSS property.
- Ems vs. Pixels
There’s
always been a strong debate as to whether it’s better to use pixels
(px) or ems (em) when defining font sizes. Pixels are a more static
way to define font sizes, and ems are more scalable with different
browser sizes and mobile devices. With the advent of many different
types of web browsing (laptop, mobile, etc.), ems are increasingly
becoming the default for font size measurements as they allow the
greatest form of flexibility. You can read more about why you should
use ems for font sizes in this
thoughtful forum thread. About.com also has a great article on
the differences
between the measurement sizes.
<editors-note>Don’t
take me to the farm on this one – but I’d be willing to bet that,
thanks to browser zooming, the majority of designers are defaulting
to pixel based layouts. What do you think? </editors-note>
- Don’t Underestimate the List
Lists
are a great way to present data in a structured format that’s easy
to modify the style. Thanks to the display property, you don’t have
to just use the list as a text attribute. Lists are also great for
creating navigation menus and things of the sort.
Many beginners use
divs to make each element in the list because they don’t understand
how to properly utilize them. It’s well worth the effort to use
brush up on learning list elements to structure data in the future.
<editors-note>
You’ll often see
navigation links like so:
- <a href="http://net.tutsplus.com/tutorials/html-css-techniques/30-css-best-practices-for-beginners/#">Home</a>
- <a href="http://net.tutsplus.com/tutorials/html-css-techniques/30-css-best-practices-for-beginners/#">About</a>
- <a href="http://net.tutsplus.com/tutorials/html-css-techniques/30-css-best-practices-for-beginners/#">Services</a>
- <a href="http://net.tutsplus.com/tutorials/html-css-techniques/30-css-best-practices-for-beginners/#">Contact</a>
Though, technically,
this will work just fine after a bit of CSS, it’s sloppy. If you’re
adding a list of
links, use an unordered
list,
silly goose!
</editors-note>
- Avoid Extra Selectors
It’s
easy to unknowingly add extra selectors to our CSS that clutters the
style sheet. One common example of adding extra selectors is with
lists.
- body #container .someclass ul li {....}
In this instance,
just the .someclass
li would
have worked just fine.
- .someclass li {...}
Adding extra
selectors won’t bring Armageddon or anything of the sort, but they
do keep your CSS from being as simple and clean as possible.
- Add Margins and Padding to All
Different
browsers render elements differently. IE renders certain elements
differently than Firefox. IE 6 renders elements differently than IE 7
and IE 8. While the browsers are starting to adhere more closely
toW3C standards, they’re still not
perfect (*cough IE cough*).
One of the main
differences between versions of browsers is how padding and margins
are rendered. If you’re not already using a reset, you might want
to define the margin and padding for all elements on the page, to be
on the safe side. You can do this quickly with a global reset, like
so:
- * {margin: 0; padding: 0;}
Now all elements
have a padding and margin of 0, unless defined by another style in
the style sheet.
<editors-note> The
problem is that, because EVERYTHING is zeroed out with this method,
you’ll potentially cause yourself more harm than help. Are you sure
that you want every single element’s margins and padding zeroed? If
so – that’s perfectly acceptable. But at least consider
it. </editors-note>
- When Ready, Try Object Oriented CSS
Object
Oriented programming is the separation of elements in the code so
that they’re easier to maintain reuse. Object
Oriented CSS follows the same principle of separating
different aspects of the style sheet(s) into more logical sections,
making your CSS more modular and reusable.
Here’s is a slide
presentation of how Object Oriented CSS works:
From Nicole
Sullivan.
If you’re new to
the CSS/XHTML game, OOCSS might be a bit of a challenge in the
beginning. But the principles are great to understand for object
oriented programming in general.
- Use Multiple Style-sheets
Depending
on the complexity of the design and the size of the site, it’s
sometimes easier to make smaller, multiple style sheets instead of
one giant style sheet. Aside from it being easier for the designer to
manage, multiple style sheets allow you to leave out CSS on certain
pages that don’t need them.
For example, I might
have a polling program that would have a unique set of styles.
Instead of including the poll styles to the main style sheet, I could
just create a poll.css and
the style sheet only to the pages that show the poll.
<editors-note> However,
be sure to consider the number of HTTP requests that are being made.
Many designers prefer to develop with multiple style sheets, and then
combine them into one file. This reduces the number of HTTP requests
to one. Also, the entire file will be cached on the user’s
computer. </editors-note>
- Check for Closed Elements First When Debugging
If
you’re noticing that your design looks a tad wonky, there’s a
good chance it’s because you’ve left off a closing </div>.
You can use the XHTML
validator to help sniff out all sorts of errors too.
- Formatting
All
CSS documents must use two spaces for indentation and files should
have no trailing whitespace. Other formatting rules:
- Use soft-tabs with a two space indent.
- Use double quotes.
- Use shorthand notation where possible.
- Put spaces after: in property declarations.
- Put spaces before {in rule declarations.
- Use hex colour codes #000 unless using rgba ().
- Always provide fall-back properties for older browsers.
- Use one line per property declaration.
- Always follow a rule with one line of whitespace.
- Always quote URL () and @import () contents.
- Do not indent blocks.
For
example:
|
.media
{
overflow:
hidden;
color:
#fff;
background-color:
#000; /* Fall-back value */
background-image:
linear-gradient (black, grey);
}
.media
.img {
float:
left;
border:
1px solid #ccc;
}
.media
.img img {
display:
block;
}
.media
.content {
background:
#fff url (".../images/media-background.png") no-repeat;
}
|
- Naming
All
ids, classes and attributes must be lowercase with hyphens used for
separation.
For
example
|
/*
GOOD */
.dataset-list
{}
/*
BAD */
.datasetlist
{}
.datasetList
{}
.dataset_list
{}
|
- Comments
Comments
should be used liberally to explain anything that may be unclear at
first glance, especially IE workarounds or hacks.
For
example
|
.prose
p {
font-size:
1.1666em /* 14px / 12px */;
}
.ie7
.search-form {
/*
Force the item to have layout in IE7 by setting display to block.
See:
http://reference.sitepoint.com/css/haslayout */
display:
inline-block;
}
|
- Modularity & Specificity
Try
keep all selectors loosely grouped into modules where possible and
avoid having too many selectors in one declaration to make them easy
to override.
For
example
|
/*
Avoid */
ul#dataset-list
{}
ul#dataset-list
li {}
ul#dataset-list
li p a.download {}
|
Instead
here we would create a dataset module and styling the item outside of
the container allows you to use it on its own example on a dataset
page:
For
example
|
.dataset-list
{}
.dataset-list-item
{}
.dataset-list-item
.download {}
|
In
the same vein use classes make the styles more robust, especially
where the HTML may change. For example when styling social links:
For
example
|
<ul
class="social">
<li><a
href="">Twitter</a></li>
<li><a
href="">Facebook</a></li>
<li><a
href="">LinkedIn</a></li>
</ul>
|
You
may use pseudo selectors to keep the HTML clean:
For
example
|
.social
li: nth-child (1) a {
background-image:
url (twitter.png);
}
.social
li: nth-child (2) a {
background-image:
url (facebook.png);
}
.social
li: nth-child (3) a {
background-image:
url (linked-in.png);
}
|
However
this will break any time the HTML changes for example if an item is
added or removed. Instead we can use class names to ensure the icons
always match the elements (Also you’d probably sprite the image :
For
Example
|
.social
.twitter {
background-image:
url (twitter.png);
}
.social
.Facebook {
background-image:
url (facebook.png);
}
.social
.linked-in {
background-image:
url (linked-in.png);
}
|
Avoid
using tag names in selectors as this prevents re-use in other
contexts.
For
Example
|
/*
Cannot use this class on an <ol> or <div> element */
ul.dataset-item
{}
|
Also
ids should not be used in selectors as it makes it far too difficult
to override later in the cascade.
For
Example
|
/*
Cannot override this button style without including an id */
.btn#download
{}
|
- Make it Readable
The
readability of your CSS is incredibly important, though most people
overlook why it’s
important. Great readability of your CSS makes it much easier to
maintain in the future, as you’ll be able to find elements quicker.
Also, you’ll never know who might need to look at your code later
on. <editors-note> when
writing CSS, most developers fall into one of two groups.
- Keep it Consistent
Along
the lines of keeping your code readable is making sure that the CSS
is consistent. You should start to develop your own “sub-language”
of CSS that allows you to quickly name things. There are certain
classes that I create in nearly every theme, and I use the same name
each time. For example, I use “.caption-right” to float images
which contain a caption to the right.
Think about things
like whether or not you’ll use underscores or dashes in your ID’s
and class names, and in what cases you’ll use them. When you start
creating your own standards for CSS, you’ll become much more
proficient.
- Start with a Framework
Some
design purists scoff at the thought of using a CSS
framework with each design, but I believe that if someone
else has taken the time to maintain a tool that speeds up production,
why reinvent the wheel? I know frameworks shouldn’t be used in
every instance, but most of the time they can help.
Many designers have
their own framework that they have created over time, and that’s a
great idea too. It helps keep consistency within the projects.
- Use a Reset
Most
CSS frameworks have a reset built-in, but if you’re not going to
use one then at
least consider
using a reset. Resets essentially eliminate browser inconsistencies
such as heights, font sizes, margins, headings, etc. The reset allows
your layout look consistent in all browsers.
The Meyer
Web is a popular reset, along with Yahoo’s
developer reset. Or you could always roll
your own reset, if that tickles your fancy.
- Organize the Style sheet with a Top-down Structure
It always makes
sense to lay your style sheet out in a way that allows you to quickly
find parts of your code. I recommend a top-down format that tackles
styles as they appear in the source code. So, an example style sheet
might be ordered like this:
- Generic classes (body, a, p, h1, etc.)
- #header
- #nav-menu
- #main-content
.
Combine Elements
Elements in a style
sheet sometimes share properties. Instead of re-writing previous
code, why not just combine them? For example, your h1, h2, and h3
elements might all share the same font and color:
- h1, h2, h3 {font-family: Tahoma, color: #333}
We
could add unique characteristics to each of these header styles if we
wanted (i.e. h1 {size: 2.1em}) later in the style sheet.
- Create Your HTML First
Many designers
create their CSS at the same time they create the HTML. It seems
logical to create both at the same time, but actually you’ll save
even more time if you create the entire HTML
mock-up first. The reasoning behind this method is that you know all
the elements of your site layout, but you don’t know what CSS
you’ll need with your design. Creating the HTML layout first allows
you to visualize the entire page as a whole, and allows you to think
of your CSS in a more holistic, top-down manner.
- Use Multiple Classes
Sometimes
it’s beneficial to add multiple classes to an element. Let’s say
that you have a <div> “box” that you want to float right,
and you’ve already got a class .right in your CSS that floats
everything to the right. You can simply add an extra class in the
declaration, like so:
<div class="box right"></div>
You can add as many
classes as you’d like (space separated)
to any declaration. <editors-note> be
very careful when using ids and class-names like “left” and
“right.” I will use them, but only for things such as blog posts.
How come? Let’s imagine that, down the road, you decide that you’d
rather see the box floated to the LEFT. In this case, you’d have to
return to your HTML and change the class-name – all in order to
adjust the presentation of
the page. This is un-semantic. Remember – HTML is for mark-up and
content. CSS is for presentation. If
you must return to your HTML to change the presentation (or styling)
of the page, you’re doing it wrong!
</editors-note>
- Use the Right Doctype
The
doctype declaration matters a whole lot on whether or not your
mark-up and CSS will validate. In fact, the entire look and feel of
your site can change greatly depending on the DOCTYPE that you
declare.
Learn
more about which DOCTYPE to use at A
List Apart.
<editors-note>
I use HTML5′s
doctype for all of my projects.
- <!DOCTYPE html>
“What’s nice
about this new DOCTYPE, especially, is that all current browsers (IE,
FF, Opera, and Safari) will look at it and switch the content into
standards mode – even though they don’t implement HTML5. This
means that you could start writing your web pages using HTML5 today
and have them last for a very, very, long time.”
</editors-note>
- Use Shorthand
You
can shrink your code considerably by using shorthand when crafting
your CSS. For elements like padding, margin, font and some others,
you can combine styles in one line. For example, a div might have
these styles:
- #crayon {
- margin-left: 5px;
- margin-right: 7px;
- margin-top: 8px;
- }
You
could combine those styles in one line, like so:
- #crayon {
- margin: 8px 7px 0px 5px; // top, rightright, bottombottom, and left values, respectively.
- }
If
you need more help, here’s a comprehensive
guide on CSS shorthand properties.
- Comment your CSS
Just
like any other language, it’s a great idea to comment your code in
sections. To add a comment, simply add /* behind the comment, and */
to close it, like so
- /* Here's how you comment CSS */
- Understand the Difference Between Blocks vs. Inline Elements
Block
elements are elements that naturally clear each line after they’re
declared, spanning the whole width of the available space. Inline
elements take only as much space as they need, and don’t force a
new line after they’re used.
Here
are the lists of elements that are either inline or block:
- span, a, strong, img, br, input, abbr, acronym
And the block
elements:
- div, h1...h6, p, ul, li, table, block quote, pre, form
- Alphabetize your Properties
While
this is more of a frivolous tip, it can come in handy for quick
scanning.
- #cotton-candy {
- color: #fff;
- float: left;
- font-weight:
- height: 200px;
- margin: 0;
- padding: 0;
- width: 150px;
- }
<editors-note> Ehh…
sacrifice speed for slightly improved readability? I’d pass – but
decide for yourself!
</editors-note>
- Use CSS Compressors
CSS
compressors help shrink CSS file size by removing line breaks, white
spaces, and combining elements. This combination can greatly reduce
the file size, which speeds up browser loading. CSS
Optimizer and CSS
Compressor are two excellent online tools that can shrink
CSS. It should be noted that shrinking your CSS can provide gains in
performance, but you lose some of the readability of your CSS.
- Make Use of Generic Classes
You’ll
find that there are certain styles that you’re applying over and
over. Instead of adding that particular style to each ID, you can
create generic classes and add them to the IDs or other CSS classes
(using tip #8).
For example, I find
myself using float: right and float: left over and over in my
designs. So I simply add the classes .left and .right to my style
sheet, and reference it in the elements.
- .left {float: left}
- .right right {float:rightright}
- <div id="coolbox" class="left">...</div>
This way you don’t
have to constantly add “float: left” to all the elements that
need to be floated.
<editors-note> Please
refer to editor’s notes for #8. </editors-note>
- Use “Margin: 0 auto” to Center Layouts
Many
beginners to CSS can’t figure out why you can’t simply use float:
center to
achieve that centred effect on block-level elements. If only it were
that easy! Unfortunately, you’ll need to use
- margin: 0 auto; // top, bottombottom - and left, rightright values, respectively.
to center divs,
paragraphs or other elements in your layout.
<editors-note> By
declaring that both the left AND the right margins of an element must
be identical, they have no choice but to center the element within
its containing element. </editors-note>
- Don’t Just Wrap a DIV Around It
When
starting out, there’s a temptation to wrap a div with an ID or
class around an element and create a style for it.
- <div class="header-text"><h1>Header Text</h1></div>
Sometimes it might
seem easier to just create unique element styles like the above
example, but you’ll start to clutter your style sheet. This would
have worked just fine:
- <h1>Header Text</h1>
Then
you can easily add a style to the h1 instead of a parent div.
- Use Firebug
If
you haven’t downloaded Firebug yet,
stop and go do it. Seriously. This little tool is a must
have for
any web developer. Among the many features that come bundled with the
Firefox extension (debug JavaScript, inspect HTML, find errors), you
can also visually inspect, modify, and edit CSS in real-time. You can
learn more about what Firebug does on the official Firebug
website.
- Hack Less
Avoid
using as little browser-specific hacks if at all possible. There is a
tremendous pressure to make sure that designs look consistent across
all browsers, but using hacks only makes your designs harder to
maintain in the future. Plus, using a reset file can eliminate nearly
all of the rendering irregularities between browsers.
- Use Absolute Positioning Sparingly
Absolute
positioning is a handy aspect of CSS that allows you to
define where exactly an
element should be positioned on a page to the exact pixel. However,
because of absolute positioning’s disregard for other elements on
the page, the layouts can get quite hairy if there are multiple
absolutely positioned elements running around the layout.
- Use Text-transform
Text-transform is
a highly-useful CSS property that allows you to “standardize” how
text is formatted on your site. For example, say you want to create
some headers that only have lowercase letters. Just add the
text-transform property to the header style like so:
- text-transform: lowercase;
Now all of the
letters in the header will be lowercase by default. Text-transform
allows you to modify your text (first letter capitalized, all letters
capitalized, or all lowercase) with a simple property.
- Don’t use Negative Margins to Hide Your h1
Oftentimes
people will use an image for their header text, and then either use
display: none or a negative margin to float the h1 off the page. Matt
Cutts, the head of Google’s Web-spam team, has officially said
that this is a bad idea, as Google might think it’s spam.
As Mr Cutts
explicitly says, avoid hiding your logo’s text with CSS. Just use
the alt tag. While many claim that you can still use CSS to hide an
h1 tag as long as the h1 is the same as the logo text, I prefer to
err on the safe side.
- Validate Your CSS and XHTML
Validating
your CSS and XHTML does more than give a sense of pride: it helps you
quickly spot errors in your code. If you’re working on a design and
for some reason things just aren’t looking right, try running the
mark-up and CSS
validator and see what errors pop up. Usually you’ll find
that you forgot to close a div somewhere, or a missed semi-colon in a
CSS property.
- Ems vs. Pixels
There’s
always been a strong debate as to whether it’s better to use pixels
(px) or ems (em) when defining font sizes. Pixels are a more static
way to define font sizes, and ems are more scalable with different
browser sizes and mobile devices. With the advent of many different
types of web browsing (laptop, mobile, etc.), ems are increasingly
becoming the default for font size measurements as they allow the
greatest form of flexibility. You can read more about why you should
use ems for font sizes in this
thoughtful forum thread. About.com also has a great article on
the differences
between the measurement sizes.
<editors-note>Don’t
take me to the farm on this one – but I’d be willing to bet that,
thanks to browser zooming, the majority of designers are defaulting
to pixel based layouts. What do you think? </editors-note>
- Don’t Underestimate the List
Lists
are a great way to present data in a structured format that’s easy
to modify the style. Thanks to the display property, you don’t have
to just use the list as a text attribute. Lists are also great for
creating navigation menus and things of the sort.
Many beginners use
divs to make each element in the list because they don’t understand
how to properly utilize them. It’s well worth the effort to use
brush up on learning list elements to structure data in the future.
<editors-note>
You’ll often see
navigation links like so:
- <a href="http://net.tutsplus.com/tutorials/html-css-techniques/30-css-best-practices-for-beginners/#">Home</a>
- <a href="http://net.tutsplus.com/tutorials/html-css-techniques/30-css-best-practices-for-beginners/#">About</a>
- <a href="http://net.tutsplus.com/tutorials/html-css-techniques/30-css-best-practices-for-beginners/#">Services</a>
- <a href="http://net.tutsplus.com/tutorials/html-css-techniques/30-css-best-practices-for-beginners/#">Contact</a>
Though, technically,
this will work just fine after a bit of CSS, it’s sloppy. If you’re
adding a list of
links, use an unordered
list,
silly goose!
</editors-note>
- Avoid Extra Selectors
It’s
easy to unknowingly add extra selectors to our CSS that clutters the
style sheet. One common example of adding extra selectors is with
lists.
- body #container .someclass ul li {....}
In this instance,
just the .someclass
li would
have worked just fine.
- .someclass li {...}
Adding extra
selectors won’t bring Armageddon or anything of the sort, but they
do keep your CSS from being as simple and clean as possible.
- Add Margins and Padding to All
Different
browsers render elements differently. IE renders certain elements
differently than Firefox. IE 6 renders elements differently than IE 7
and IE 8. While the browsers are starting to adhere more closely
toW3C standards, they’re still not
perfect (*cough IE cough*).
One of the main
differences between versions of browsers is how padding and margins
are rendered. If you’re not already using a reset, you might want
to define the margin and padding for all elements on the page, to be
on the safe side. You can do this quickly with a global reset, like
so:
- * {margin: 0; padding: 0;}
Now all elements
have a padding and margin of 0, unless defined by another style in
the style sheet.
<editors-note> The
problem is that, because EVERYTHING is zeroed out with this method,
you’ll potentially cause yourself more harm than help. Are you sure
that you want every single element’s margins and padding zeroed? If
so – that’s perfectly acceptable. But at least consider
it. </editors-note>
- When Ready, Try Object Oriented CSS
Object
Oriented programming is the separation of elements in the code so
that they’re easier to maintain reuse. Object
Oriented CSS follows the same principle of separating
different aspects of the style sheet(s) into more logical sections,
making your CSS more modular and reusable.
Here’s is a slide
presentation of how Object Oriented CSS works:
From Nicole
Sullivan.
If you’re new to
the CSS/XHTML game, OOCSS might be a bit of a challenge in the
beginning. But the principles are great to understand for object
oriented programming in general.
- Use Multiple Style-sheets
Depending
on the complexity of the design and the size of the site, it’s
sometimes easier to make smaller, multiple style sheets instead of
one giant style sheet. Aside from it being easier for the designer to
manage, multiple style sheets allow you to leave out CSS on certain
pages that don’t need them.
For example, I might
have a polling program that would have a unique set of styles.
Instead of including the poll styles to the main style sheet, I could
just create a poll.css and
the style sheet only to the pages that show the poll.
<editors-note> However,
be sure to consider the number of HTTP requests that are being made.
Many designers prefer to develop with multiple style sheets, and then
combine them into one file. This reduces the number of HTTP requests
to one. Also, the entire file will be cached on the user’s
computer. </editors-note>
- Check for Closed Elements First When Debugging
If
you’re noticing that your design looks a tad wonky, there’s a
good chance it’s because you’ve left off a closing </div>.
You can use the XHTML
validator to help sniff out all sorts of errors too.
No comments:
Post a Comment