PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

CSS Tips

Here is a list of CSS-related tips. They are basic things you can do within your CSS file and/or HTML files to make your pages:

  • Faster to download
  • Faster to render
  • Work in more browsers (and look the same!)
  • Be accessible
  • Be maintainable

Whenever possible, you should use external stylesheets, as opposed to include the CSS directly in your XHTML document.

This will reduce the filesize of your web pages, and therefore speed up the download, and perhaps even save you bandwidth charges. Both snippets below should appear within the <head> tag.

Listing 1 listing-1.html
<link rel="stylesheet" type="text/css" href="/css/styles.css" />

You can also use the @import directive, although personally I’ve had trouble using this method when trying to include separate screen and print stylesheets in Internet Explorer.

Listing 2 listing-2.html
<style type="text/css">
    @import '/css/styles.css';
</style>

There are many tags and attributes previously used in HTML for layout and formatting. Many of these are now deprecated, and generally have a replacement in CSS.

Examples:

Listing 3 listing-3.html
Bad:  <table align="center">
Good: <table style="margin: auto">
 
Bad:  <td valign="top">
Good: <td style="vertical-align: top">
 
Bad:  <body bgcolor="#FFFFFF" marginwidth="10" marginheight="10"
                              leftmargin="10" rightmargin="10" topmargin="10">
Good: <body style="background: #fff; margin : 10px;">

There are many more, although some may only be achieved using a style sheet rather than using the style attribute. The style attribute was only used for the purpose of this example – see the next section for more on this.

It is good practice to avoid ever using the ‘style’ attribute in your XHTML code. There are several reasons for this:

  • It makes your source code bloated and hard to read.
  • The code is not very portable – to other devices and browsers
  • It is difficult to maintain (for example, if you need to update your site)

It may take a little bit of work and thinking, but it is fairly simple to avoid to using the style attribute by carefully using CSS classes and ID’s. You can use the other tips in the article to see how to avoid using the style tag.

This is a fairly common question when moving away from deprecated tags. Especially since some browsers default this to a value greater than 0. The answer is the border-collapse property.

Here’s an example:

Listing 4 listing-4.html
Deprecated:
 
    <table cellspacing="0" cellpadding="3" border="1">
        <tr>
            <td>Example</td>
        </tr>
    </table>
 
Doing this in CSS:
 
    <style type="text/css">
        table { border-collapse : collapse; }
        td { padding : 3px; border : 1px solid #000; }
    </style>
 
    <table>
        <tr>
            <td>Example</td>
        </tr>
    </table>

This looks longer, but obviously when placed in a stylesheet and reused many times it will be much shorter – as you can see, the table markup is much shorter.

Many people make the mistake of reusing ID’s between tags. The point of an ID to identify a single element in a HTML document. If you want to style multiple items in the same way, you use classes.

Listing 5 listing-5.html
Incorrect:
    <p id="some-style">
        Para 1.
    </p>
 
    <p id="some-style">
        Para 2.
    </p>
 
Correct:
    <p class="some-style" id="para-1">
        Para 1.
    </p>
    <p class="some-style" id="para-2">
        Para 2.
    </p>

Not every element needs an ID tag, but if you need to reference it with specific CSS tags or for JavaScript then it will.

It’s still a common practice to specify border="0" on images that are hyper-linked. In fact, this is deprecated, and there is a much simpler solution, as borders are very rarely used on images anyway.

Listing 6 listing-6.html
<style type="text/css">
    img { border : 0; }
</style>
 
<a href="#"><img src="/path/to/image.jpg" /></a>

You’ll often see some text sitting right next to a form input, but it never seems to line up properly. Again, a simple fix for this – simply set the vertical alignment of the form elements to middle:

Listing 7 listing-7.html
<style type="text/css">
    input, select { vertical-align : middle; }
</style>
 
Username: <input type="text" name="example" />

You may not understand what I’m going on about here until you actually try it – with and without changing the vertical alignment.

This is an ongoing argument to do with how to structure your web pages. As a result of this argument, some people believe it is bad to ever use tables. This is totally incorrect it. The reality is:

  • Tables should be used for tabular data
  • Divs should be used whenever possible for defining a page structure, using floats, positions and margins.
  • Divs don’t always easily allow you to do this and sometimes tables are required.
  • Whether you use tables or divs, use them wisely – table soup is nasty but it is also possible to make soup out of divs.
  • However you do it, make sure it validates!

Here’s an example of where divs should be used over tables for defining site structure. The output of both method 1 and method 2 should be identical.

The code will define a fixed-width centred structure. The text included is just text to demonstrate some content, but realistically inside the cell or div would be further structural elements such as navigation, headers and footers.

Listing 8 listing-8.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <style type="text/css">
            body {
                background-color : #f7f7f7;
            }
            #sample1 {
                border-collapse : collapse;
                width : 510px;
                background-color : #fff;
                border-left : 1px solid #000; border-right : 1px solid #000;
            }
            #sample1 td {
                padding : 5px;
            }
 
            #sample2 {
                margin : auto; padding : 5px;
                width : 500px;
                background : #fff;
                border-left : 1px solid #000; border-right : 1px solid #000;
            }
        </style>
    </head>
 
    <body>
 
        <!-- Method 1: Using tables -->
        <table id="sample1" align="center">
            <tr>
                <td>Sample text</td>
            </tr>
        </table>
 
        <hr />
 
        <!-- Method 2: Using divs -->
        <div id="sample2">
            Sample text
        </div>
 
    </body>
</html>

Notes:

  • There is less HTML and less CSS required for the div version.
  • Due to the difference in rendering padding between table cells and divs, the widths are diff
  • This method may not be compatible on Internet Explorer versions less than version 6
  • The DOCTYPE is required for this to work in Internet Explorer 6 – note that XHTML 1.0 Transitional will also work.
  • This document won’t validate as XHTML 1.0 Strict because of the align="center" attribute, however, since we recommend against this method it doesn’t particularly matter – the div code is XHTML 1.0 Strict compliant.

It is very easy to overdo styling of elements, and also unnecessarily applying classes to various element.

A good example of this is when doing a list of links, say for site navigation. I have often seen (and probably done it myself) every link in a block with a class applied, rather than simply applying to style to the surrounding block.

Here’s an example of what is bad:

Listing 9 listing-9.css
    a.navLink { font-weight : bold; }
Listing 10 listing-10.html
    <a href="/link1" class="navLink">Link 1</a>
    <a href="/link2" class="navLink">Link 2</a>
    <a href="/link3" class="navLink">Link 3</a>
    <a href="/link4" class="navLink">Link 4</a>

A way to improve this would be to do it as follows:

Listing 11 listing-11.css
    #navigation a { font-weight : bold; }
Listing 12 listing-12.html
<div id="navigation">
    <a href="/link1">Link 1</a>
    <a href="/link2">Link 2</a>
    <a href="/link3">Link 3</a>
    <a href="/link4">Link 4</a>
</div>

Of course, this is subjective and depends on your circumstances. This is a fairly simple example, but hopefully it demonstrates the point of unncessarily overdoing CSS.

Nearly every large content site on the Internet is guilty of this – providing a link which opens a “printer friendly” version of the content you’re looking at. Don’t get me wrong, it’s good that they do this, but it’s unnecessary.

Mind you, because it’s common practice, it’s going to be hard to break this trend any time soon.

Anyway, it is possible to include a separate stylesheet in your document specifically for printing, so a user can print a page without having to open a separate printer friendly page.

If you’re not sure what I mean here, use your “Print Preview” tool (if you have one), to see that this article will print differently to paper than how you see it on screen. The top bar is gone, the left and right navigation, as well as all advertising is stripped out.

This achieved using the following HTML code:

Listing 13 listing-13.html
<link rel="StyleSheet" type="text/css" href="/css/default.css" media="screen" />
<link rel="StyleSheet" type="text/css" href="/css/default-print.css" media="print" />

The media attribute of the above tags defines when each stylesheet should be used. So by using media="print", a stylesheet will only be used when printing.

In this stylesheet, we hide the navigation by using the CSS display property.

Listing 14 listing-14.css
#primary-nav-container { display : none; }

Additionally, there may be other stylings you want to change, such as font size or colours. You may notice the print logo for PhpRiot is an inverted version of the normal logo. This is achieved by including both logos on the page. In the main stylesheet, the inverted logo is hidden, and on the print stylesheet it is shown, while the main logo is hidden.

One of the biggest hints to take on board when trying to make your site look the same in say Internet Explorer and FireFox, is to remember that they use different default values for certain elements.

The best example of this is with unordered lists. Internet Explorer uses no padding, but it does use a margin on the <ul> tag, whereas Firefox uses both a padding and a margin. So if you ever try to change the margin-left of unordered list items, the effect will work in Internet Explorer, but not Firefox.

All you need to do is set padding to 0 in Firefox for this element and it will work the same as Internet Explorer.

  1. CSS 2.1 Specification
  2. W3C CSS Validator
  3. Style-Sheets.com list of deprecated HTML tags and attributes

Other Options

CSS Tips