CSS Best Practices

CSS Best Practices for a Better Layout

Cascading Style Sheets have now become the standard way of adding the look and feel to a website. Virtually all the older HTML3 style commands have now been consigned to history and deprecated in HTML4 and most have been dropped completely in HTML5.

For developers returning to HTML writing after a few years break this reliance on the “new” CSS way of doing things can seem odd. It is however much simpler and web pages using CSS style sheets are much smaller and clearer. Using the HTML 3 styling meant you had to have lots of size, color, and positioning code cluttering the pages. All of this style clutter had to be repeated every time you wanted to use it, so for instance the ‘center’ command was always required before a text section you wanted to centralize. It is amazing to see how much larger an old web page is with the older styling in comparison to the same CSS formatted page. Even if you are only dealing with one page, separating the styling from the content makes it simpler and easier to deal with.Below mentioned are some of the CSS best practices that must be applied in order to have a good look and feel.

Style Sheets

There are three ways to include cascading style sheets. These are external style sheets, internal styling and inline styling.

The external style sheets are the most powerful and should be used as best practice. An external file holds the styling instructions and is linked into the HTML page that will use the styles. Using external style sheets allows a site to be smaller because the same style sheet can be used on many HTML pages; it also speeds up download times and reduces the storage space required. The styles are written as plain text and generally the external style sheet has a .css extension.

Internal style sheets are useful during development. The internal style sheets can be copied to an external style sheet once it has been developed.

Inline styling is a throwback to the old system of using style instructions for each tag on a page. It is long winded to write and is error prone to update. Inline style may not validate, depending on the doc type, so to future proof sites its best to avoid this.

Note: For the sake of future proofing make sure all the HTML is in lowercase and that all attributes are enclosed in speech marks. This enables it to be verified in XHTML as well as HTML.

The Use of Classes

Classes use a period (.) to identify that the item is a class. These are used to specify the style class to which the element belongs. For example, the style sheet may have created the ‘main header’ and ‘warning’ classes:

.main-header { color: lime; background: #ff80c0 }
p.warning { font-weight: bolder; color: red; background: white }

These classes could be referenced in HTML with the class attribute:

<h1 class="main-header">Proprietary Extensions Explained</h1>
<p class="warning">This is a warning</p>

How to Select HTML to Style

To apply a style to a bit of HTML it has to be selected. The part of the CSS style before the curly bracket is the selector and the bit between the brackets is the style to apply. It has the following form:

Selector list { Styles to apply to selected item }

The styles are separated by a semi colon. There can be many styles. The selector list can be one or more HTML tags, classes or Ids. The simplest selector will comprise a single class or tag, for example:

body { background-color: silver; }

Here the background color of the page is silver. The silver color applies to everything within the body tag, which is the whole page. Other tags, such as Divs and Paragraphs, will all inherit this color unless you change it specifically.

To make a selector target something more precisely you can add additional items to the selector list, as this example demonstrates:

p h3 { font-weight: bolder; color: red; }

Note the space between the p and the h3. The space tells the browser that it must style any h3 tag that is contained in a paragraph, or put another way, that any h3 heading that is a descendant of a paragraph tag must be styled.

The Use of Pseudo Classes

A Pseudo class is a series of properties that relate to one element. For instance in the case of an anchor you have the link, visited, hover and active pseudo classes. These are written with a colon after the element.

The visited pseudo class for an anchor is written as:

a:visited { color: blue; }

This allows you to add styles to any visited link, replacing the default purple underlined link with blue in this case.

Using Multiple Style Sheets

It can be hard to workout which styles may conflict when a page imports multiple CSS’s. A page may use internal style sheets too for added fun! To help reduce import conflicts try to use the style sheets in the same order and make sure internal styles are defined below the links to external sheets. This provides a consistent way of using the style sheets across the entire site and allows you to understand how everything interacts.

In the sample below we show how external style sheets can be used.

<!-- External Style Sheets -->
<link type="text/css" rel="stylesheet" href="/css/global.css" />
<link type="text/css" rel="stylesheet" href="/css/reset.css" />
<!-- Internal Styling-->
<style type="text/css" >
     body { background: url (‘/images/bg.gif’) red; color: black }
     note { margin-left: 5px; margin-right: 5px }
</style>

Overriding Attributes With !Important

To make sure a style option is implemented you can use !important. This effects one attribute of a style only, not the whole style.

In this example the text-align is marked as !important. Other text-align’s will be ignored because of the !important, even if they have a higher weighting.

p {
color: blue;
text-align: center !important;
font-family:'Times New Roman', 'serif';
}

Only the text-align is marked as !important and the color and font-family attributes will behave as normal.

Note: Use !important sparingly so things behave as expected when you update the styles. It’s frustrating to discover after ages of searching that an !important is why things are not behaving as they should!

It is better to make sure the tag you want styled is fired using the correct selectors. However !important is a last resort to style something the way you really want it.

Browsers Have Style Sheets of Their Own

A Browser has its own style sheet and this is different by brand, so Chrome’s default style will not be the same as Firefox’s and Internet Explorer 9 has a different style to Internet Explorer 6. This can lead to your web pages looking different in one browser to another.

To make sure the styles you create look the same in all browsers you need to reset the browser’s own style sheet.

To make the browsers all sing from the same style sheet it is recommended to reset the styles for the following tags :

html, body, h1, h2, h3, h4, h5, h6, p, ol, ul, li, dl, pre, code, address,
variable, form, fieldset, blockquote, label, img

You should set the padding, the margins, the font size and the font weight to what you want. The list items should have their margins and list styles set to your chosen options.

Once all these have been set to how you would like them to appear they should be added to the global CSS sheet. These will then be included in every site and page you create. You may decide to not bother with this and live with the differences. If it’s crucial your sites are as alike from browser to browser you will want to make these changes.

EM Measure

The em measure works in the same way as percentages. To increase a font size by two and a half times using the em measure you use the following tag :

sample { font-size: 2.5em; }

There must be no spaces between the em and the number. The same applies for setting size in percentages and pixels.

The Box Model

The box model defines how elements are placed on a page. Understanding how the model works will allow you to determine how much space a tag will need. It deals with the margins, borders and padding that surround the tag contents.

A tag is surrounded by a layer of padding which produces a space between the contents and the surrounding area. Next we have a border that can frame the contents. Around the padding and the border there is a margin. The padding, border and margin can be set for individual sides, or not at all.

To work out the total width you need to know the image width, the padding, both left and right, the border widths, both left and right, and the left and right margin widths.

These sections all have a top, right, bottom and left section. They can be set directly or they can be set via a short hand method. Here is an example that sets the margins on all sides of the heading to zero and adds a padding of 10 pixels to all the four sides.

h1 {
margin: 0;
padding: 10px;
}

When a value is zero you do not need to add any measurement type.

To set the padding for the all the sides using the short hand method use the following:

sample-box { padding: 10px 5px 20px 5px; }

The padding and margins are set using this order: top, right, bottom and left.

To set all the margins individually use the following:

sample-box {
margin-top: 10px ;
margin-left: 5px;
margin-bottom: 20px;
margin-right: 5px;
}

If you want to set the top and bottom and the left and right values to the same, you can use this short cut:

sample-box { margin: 5px 10px; }

Here the top and bottom margins are set to 5px and the left and right margins are set to 10px.

These short cuts work for the border and the padding as well.

The Border can be styled using the border-style tag. You could have a solid border or a dashed one etc, to give varying effects. The border width can also be set using the border-width tag. These effects can be applied to one or more of the sides using the left, right, top and bottom tags.

To make the border on the right three pixels wide and solid use the following tags:

sample-box {
border-right-width: 3px;
border-right-style: solid;
}

The box model formatting is not the same in all browsers. The way the box model gets padded out and the way it adds default margins etc, are determined by the browsers own style sheet. Therefore it’s advisable to reset the browser styles as described before to be sure you get what you want and not what the browser thinks you want.

The Overflow Property

When the contents of an element will not fit into its height or width it may overflow out of the element at the sides or bottom. If this is text then the text from a notice box may run into the text of the rest of the page. This makes the page badly designed and may make it impossible to read.

Most browsers allow the overflow and leave you to sort the issues out. However IE8 and earlier will allow extra space for the overflow by expanding the box, but this will probably alter the look of the page, so it still needs you to fix it properly!

The overflow tag allows you to control the way it deals with the issue. There are four options: visible, scroll, auto, and hidden.

The tag is used like this:

sample-box { overflow: scroll; }
  • Visible is the browser default and doesn’t need to be set.
  • Scroll adds scrollbars to the container. The problem is it always adds the scroll bars and looks poor.
  • Auto adds scrollbars only when they are needed.
  • Hidden hides the overflow. This doesn’t look bad, but means information is lost from your page, which is not going to please your readers at all.
  • Internet Explorer Tip: To stop IE always displaying a vertical scrollbar you need to set the overflow tag to auto in the style that affects the body element of the page.

Using Images with CSS

Images can be added into your web pages with the HTML ‘img’ tag or using the CSS background-image tag.

It is possible to use images on your web pages and never use a single ‘img’ tag! CSS images can transform the look and feel of a site.

Images are imported using the background-image tag in the style sheet. In the following example an image is loaded into the body and repeats down the page:

body {
background-image: url(‘images/brushed-metal.gif’);
background-repeat: repeat-y;
}

Here the images folder is in the same location as the CSS or the HTML page, if it’s an embedded style.

Locating Images

In general when using images via a style sheet, the image is located relative to the calling style sheet and not the web page. If the style is embedded, or inline, then the web page and CSS are located in the same place.

There are three ways that you can tell the CSS where the image you want is located. The first is to be absolutely specific using the full web URL. While this always works, it works only when the site is being used via a web server, so it is not that suitable for development unless you deploy the site to a server for testing, which can be a slow process. Using URL’s also makes updating the image locations more painful. The following example shows this method:

body {
background-image: url("http://www.images.com/buttons/macButton.gif");
}

The second way to locate images is relative to the calling CSS. This allows images to be located at design time by double clicking and requires no server to test. For instance if the CSS style sheets are located in a folder in the root directory called css_store, and the images are in a folder located in the root directory called image_store, then the CSS path to an image would be:

<img src="../image_store/button.gif" alt="button" />

The .. tells the computer or server to go up one directory, so it goes up to the root here, then it goes into the image_Store directory and locates the button.gif stored there. The tag to locate the button in the image in this case is:

body {
background-image: url(‘../images/button.gif’);
}

The third way is to use a path that always originates at the root of the web application.

body {
background-image: url(‘/images/buttons/macButton.gif’);
}

The leading slash tells the computer this address starts in the web application’s root directory. For this example to work a folder called images, with the buttons folder in it, would need to be located in the root directory. This also will only work when the page is sent to the user by a server. If you double click, or load the web page manually, the image will not appear. The alt text or a blank image holder will be displayed. An advantage of this method is that the path is always the same where ever it’s called from.

If you want a background image to remain in a fixed location and not move when the page is scrolled, use the following:

header-image { background-attachment: fixed; }

This works well when you have an image, a logo for instance, you want to underpin a page.

Positioning CSS Background Images Using Keywords

Images can be positioned on a page using the following properties:

left, right, center, top, bottom

The following is an example of a background image that is positioned at the top center of the page’s body:

body {
background-image: url(‘body-bg.png’) ;
background-position: top center;
}

You use the background-repeat to control whether it is repeated vertically or horizontally on your page. If you don’t provide a repeat instruction, the background image will be tiled across and down the page.

To make the image repeat down the page use this:

body { background-repeat: repeat-y; }

To make the image repeat across the page use this:

body{ background-repeat: repeat-x; }

Positioning CSS Background Images Using Values

Images can be positioned on a page using percentages, pixels or em measurements. The measurements origin is in the top left corner of the page and the measurements are used like this:

body { background-position: 20px 100px; }

Here the image will be 20 pixels from the left and 100 pixels from the top of the page.

Using pixels or em’s can help tweak the location of bullet point images, and other graphics, when you want full control over where an image will appear.

The Short Cut Way to Use Background Properties

It is possible to combine all the properties into one line using just the background property. It uses a list of attributes in the following order: color, image, location, attachment and position.

An example of this is:

body { background: white url(‘logo.gif’) fixed center center no repeat; }

Here the background is set to white and a logo is loaded into the center of the page and it does not repeat or move.

You do not need to use all the attributes when using the shorthand property. In the next example the background color is set and the image is allowed to move:

body { background: #ff10ff scroll; }

Here is an example of fixing a background image so it doesn’t move:

body { background: url(‘logo.gif’) fixed; }
Like & Share

Leave a Reply