CSS Basics - How to code better
Posted: April 22nd, 2009 | Author: Ryan | Filed under: CSS | Tags: Better Coding, CSS, Shorthand | 1 Comment »1. Comment your code
Commenting code is a practice often overlooked when working to a deadline.
Using comments on any web source coding language can easily distinguish each part of the design you are working on. Helping further down the line when maintenance or tweaking is needed to inject life into your site.
fig 1. (CSS Comments)
/* This is an example of a CSS comment than can span over
several paragraphs */
// This is used for single lines only
2. (Shorthand CSS)
Shorthand CSS is a method of writing CSS code in more condensed manner
fig 1. (Long hand CSS)
#example {
margin-top: 0;
margin-right: 1px;
margin-bottom: 2px;
margin-left: 3px;
}
fig 2. (Short hand CSS)
#example {
margin: 0 1px 2px 3px;
}
The CSS code created using shorthand is smaller in file size in comparison to using the longer version in fig 1.
When using shorthand notice that when a value of 0px is needed that it is written using just a 0 without the px value at the end.
Shorthand can be used with the margin, border and padding delimeters.
The CSS can be further shortened to
#example {
margin: 0 1px 2px;
}
this will give the margin properties of
#example {
margin-top: 0;
margin-right: 1px;
margin-bottom: 2px;
margin-left: 2px;
}
also using only two values in the shorthand will give
#example {
margin: 0 1px;
}
versus
#example {
margin-top: 0;
margin-right: 1px;
margin-bottom: 0;
margin-left: 1px;
}
Finally only using one value in shorthand will give a uniform value for all four declarations of the delimeter.
3. Abandon Inline styles and migrate to external sheets
Using external style sheets will allow for your web pages to load faster, less code = less time.
By grouping common styles in classes together in a separate file the mark-up language used to generate each page is reduced and not repeated making redesign and maintenance easier and less of a headache for you later on.
To use an external style sheet simply place the following code within the head portion of your html document.
<style type=”text/css”>@import url(monochrome.css);</style>