Home Learning cascading style sheets Programming Web Design

Advanced Cascading Style Sheets

What is a cascading style sheet?
Before looking at advanced techniques for CSS it is important to ask the question what is a cascading style sheet? This is needed to understand why some of the techniques I will look at work. Most designers have a rough idea about what a stylesheet is but to use them properly you need to understand exactly what is meant by a cascading stylesheet.

Cascading
A cascade is a waterfall; the word seems to indicate something coming down. It is a beautiful word.
In the case of a stylesheet cascading is used to indicate that one stylesheet affects others within a single document – because one document can contain many stylesheets.
In the case of CSS the cascading is exactly definable. We can exactly predict the way one stylesheet will affect another one – with mathematical precision.
Consider the following example:
p{
font-size:12px;
font-family: Arial;
color: red;
}
If this is included in stylesheet ‘A’ it will produce a default paragraph of Arial font 12 pixels red in colour. If I further include a second stylesheet ‘B’ with the following definition
p{
color: blue;
}
The default paragraph will now be Arial of 12 pixels high but blue in colour.
Therefore we can think of the total stylesheet as follows:
Screen output = Stylesheet A + Stylesheet B + Stylesheet N

You may ask why anyone should want to include more than one stylesheet in one document? Well you may define one with generic styles for an entire site and a second set one for each area of a site. Thus you would get two sheets generic_styles.css and local_styles.css. You could also have generic styles and home styles for example. Additionally a browser has a default style sheet and a user can also potentially set a stylesheet up for all pages – e.g. if that person had problems with reading small print. The fact that browsers have default styles is very important because different browsers can obviously have different default styles.
The example below is for a DIV layer defined as follows:
 

<div id="”leftnav”">some content</div>


The stylesheet entry is as follows
#leftnav p{
font-family:Tahoma;
}
In this case the default paragraph style will be adopted, so it will be 12 pixels, blue in colour but using font Tahoma.
The paragraph for the DIV layer inherits from the default p style but adds the font Tahoma. This brings us nicely onto the topic of inheritance.

 

Like father like son - inheritance
The rules of cascading stylesheets are far cleverer than the type of cascading I mention above, because they include the idea of inheritance – if you really want to understand CSS you also need to understand inheritance – it is a vital part of the whole.
It is normally fairly easy to guess the way HTML entities are related together, for example, it is fairly easy to guess that probably inherits its attributes from

will inherit arial font. It is equally pretty fair to assume that most entities inherit from simply because the tag nests all entities in an HTML document, so if I set body{font-family: Arial, Helvetica, "sans serif"; } it is fair to assume that Arial will be the default font for any document including that stylesheet.

 

But this is an assumption that is only safe in certain contexts. The diagram below outlines a tree structure for an HTML document. The section is taken from Lie and Boss
http://www.w3.org/Style/LieBos2e/enter/
“The tree structure of this document is:
[image]
Through inheritance, CSS property values set on one element will be transferred down the tree to its descendants. For example, our examples have up to now set the colour to be green for h1 and h2 elements. Now, say, you would like to set the same colour on all elements in your document. You could do this by listing all element types in the selector:

However, most HTML documents are more complex than our sample docu­ment, and your style sheet would soon get long. There is a better - and shorter - way. Instead of setting the style on each element type, we set it on their common ancestor, the body element:

 Lie and Boss Chapter 2

Text Box: Browser ‘mood’ FirefoxIt is easy to believe that “somebody up there” has it in for you when working with CSS and inheritance, because not all attributes inherit, and sometimes things inherit that you wish wouldn’t. Background image does not inherit – and this is good. However, margin and padding seem to inherit depending on browser ‘mood’ or time of day – or perhaps a mixture of these. In fact there is a set of rules, these rules relate to the box model used by CSS.
The place to start learning about margins and padding is in http://www.w3.org/TR/REC-CSS2/box.html

A common work around for problems related to box model is by setting the margin and padding of all elements to zero then overriding this setting as needed this can be achieved as follows:
*{margin: 0px; padding: 0px; border: 0px;}
(note use of the wildcard *).
This little trick transformed my life when working with CSS and avoided many white hairs. It just says - set a margin, border and padding of zero pixels for all elements!
There are some notable downsides to doing this and you need to be aware of them – for example, forms loose default buttons etc when you set borders and margins to zero, also borders disappear from text boxes making them invisible. But if you intend to define your own text boxes and buttons anyway then it is fine to start with everything set to zero. Another and perhaps better idea is to set all the margins and borders for a single DIV layer to zero. This can be achieved as follows:
#layername * {margin: 0px; padding: 0px; border: 0px;}

It is worth noting that in the inheritance hierarchy

is one stage below and above elements such as

and

  • . So if you use a layer everything nested within that layer inherits its attributes.

     

    Declared inheritance

    With CSS you can tell one element that it is to inherit the attributes of a different element. Consider the following classes:
    .ClassA{
    font-family:Arial;
    font-weight:bold;
    font-size:0.75em;
    }
    .ClassB{
    border:1 solid black;
    }
    If I wish to share the attributes of ClassA with ClassB I can declare this in the following manner:
    class=”ClassA ClassB”

    One can also declare that an attribute of one entity is inherited from the same attribute of a nesting entity:
    p{
    font-family:inherits;
    }
    Also consider the following:
    p,li{
    font-family:arial;
    font-size:0.75em;
    line-height:1.25em;  
    }
    li{
    margin-left:20px;
    }
    In this case we wish

  • and

    to use the same style apart from indentation, we wish the

  • tag to produce an indentation of 20px.
    This shows how by redefining part of a style, I can minimise the length of my style sheet.
    If I had defined the body tag as:
    body{
    font-family:arial;
    }
    Every element would be in font – arial because every other element inherits the font attributes of . See Lie and Boss above.

     

    Table-less design using divs (layers)

    Why use DIVs?

    What most designers want is a series of easy steps they can follow in order to produce a beautifully designed web page, it would also be pretty nice too if the web page worked on a range of different browsers and continued to work for a number of years. What a table-less layout offers is design using a set of standards that has been universally accepted by software vendors and designers alike. These standards have been devised by W3C using CSS2.
    Why abandon tables?
    The first point to make is that tables were never intended to be layout or design objects, a table rather is supposed to be a tabular device to hold data when spread-sheet like presentation is required. If it is used as such – that is fine, but if it is being used for design then technically it is being misused.
    Layers by contrast always have been layout objects. They were originally designed as such; however, different browsers required different syntax for layers – what is more they proved amazingly difficult to use for standard web design. So designers turned to tables instead.
    Recent advances is CSS now mean that DIV layers are far easier to use and more reliable. Using table-less design:

    • meets accessibility requirements;
    • means that pages index better on search engines;
    •  makes it easier to provide a common standard for websites;
    • makes pages far smaller (quite often by 300 to 400 percent) – this can significantly speed up server operation;
    • are easier to use for layout than tables – once you have understood the basics of layers.

    XHTML

    The Extensible HyperText Markup Language, or XHTML, is a markup language that has the same expressive possibilities as HTML, but a stricter syntax. It uses the same standards as XML (Extensible Markup Language -  a simple, very flexible text format which is also playing an increasingly important role in the exchange of a wide variety of data on the Web and elsewhere.) XML is easier to parse and process than HTML, XHTML is also easier to parse. Therefore XHTML is more portable than HTML. It can be used on mobile devices like phones where browser cross compliance, page size and CPU speed are an issue.  Typically XHTML pages are smaller and simpler than HTML pages. In the case of the AHS website the home page reduced from 32k to only 8k when coded using XHTML. The size of the style sheet also was reduced. This manual is written for XHTML and not HTML.

    Document Type Definition files .dtd

    Document types give XHTML and stylesheets a framework on which to build a document. This framework defines which entities are allowed in the document and the relationship of these one to the other. In XHTML the doctype is the very first thing in the document prior to the tag.
    XHTML 1.0 defines three doctypes namely transitional, strict and frameset. Since we do not normally use frames we can forget the frameset definition. The choice becomes between strict and transitional. The transitional document types allows a number of traditional HTML layout features whereas the strict type leads to clean and simple markup free from presentational clutter. Dtd files originate from XML see above.
    Transitional is as it says – a transition (half way between HTML and XHTML). It seemed to me better to go the whole hog – strict gives a presentationally cleaner model and helps reduce the rendering differences on browsers.
    http://www.w3schools.com/tags/tag_doctype.asp

    Webs using 3 stage design

    The process I use for designing CSS is a three stage process. This process could be describe as Measure, Draft, Refine. The three stages are as follows:

    • Sketch the design and work out all the measurements for the page.
    • Put together a rough draft using div tags, referenced by id in the stylesheet, for unique areas of the screen. Use DIV tags with classes in the stylesheet for repeating areas.
    • Solve small stylistic and browser issues and complete stylesheet

    Here is a working example of a 3 stage design process. The website in question is the Faculty of Arts and Human Sciences at London South Bank University.

    Stage 1 – measure and sketch the design
    Firstly if we have a design to work on a rough sketch of the design is a starting point. Then you will need to work out the required divs. To do this you need to work out unique areas of the screen. Each area can adopt an ID.

    Stage 2 –design rough draft
     

    Text Box:    My rough sketch of the AHS home page with pixel sizes

     

    The image below shows the approximate division of the page into DIVS.
    Text Box:

     

    Two areas .title and .addlinks are classes. This is because these areas repeat so using a classes makes sense. You should not use the same DIV more than once!

     

    I could also have redefined the hyperlink for the area bottomnav rather than using the class .addlinks – doing this would have been far more efficient. So if I were to add a second stage to my refinements, I would remove .addlinks and redefine for bottomnav. To do this I would simply declare:
    #bottomnav a{
    CSS details
    }

    The class .title however needs a header and then a series of hyperlinks. So using a distinct class makes more sense.
    Stage 3 Refine
    Once the style sheet is coded it needs testing in different browsers and tweaking accordingly – this refinement process can also iron out small stylistic difficulties. Refinement is an iterative process.

    Let’s go through all the layers I chose to create one by one.
    First, I defined an area with the id of ‘topnav’ for the banner and logo. Essentially this area contains two images one of which aligns left and the other aligns right. The area has a background colour of grey – and that is all that is needed. The layer uses the display attribute of ‘block’ this ensures that the area displays as a ‘block’. Float:left ensures that the layers align left in the first available slot. 

    Next I need an area for the news strap line and search box. In this case I also need to incorporate a form and I need to cope with a range of hidden fields.

    I created a second div for the form with the id of searchbox.

    The reason for this choice was that I needed the form on the right hand side and the news counter on the left – in the layer searchbox I used the command – float:right. I decided to redefine for searchbox – and I needed to ensure that all the hidden fields actually were hidden (because if you redefine input as a block and give a border the hidden fields will appear as empty squares).

    Then I created a class for the input box holding text.

    The resulting CSS for this layer is below:

    #searchbox{  
    padding:0px;
    margin:0px;
    width:200px;
    display:block;
    float:right;
    background-color:#CCCCCC;       
    height:31px;
    text-align:right;
    }
    #searchbox input,form{
    vertical-align:middle;
    }
    #searchbox input.inputbox{
    background-color: #FFFFFF;
    border:1px solid #94979E;
    height: 20px;
    width: 114px;
    }

    One point to note here is that I have started off with a padding and margin of 0px and then re-defined these elements as necessary.

    The next area is the main body area. On the face of it this appears the most difficult one to design. In actuality I managed to put this together in an hour or so.
    A wrapping class .contentcols produces each of the three columns:
    .contentcols{
    float:left;
    width:170px;
    display:block;
    margin-right:5px;
    background-color: #F0F0F0;
    }
    Each title is achieved by a nested DIV with the class .title to which is added a second class to achieve the different colours for each header (e.g. education – blue; psychology – purple).
    So for example we get  

    for the header of psychology. This class takes all the attributes of title but adds the image for psychology.
    Below is the HTML for the div for psychology

     

     

    Here is the CSS for the same area:
    .title,.titleuel{
    color: #FFFFFF;
    font-size: 0.7em;
    line-height: 0.95em;                   
    margin-bottom:8px;
    font-weight: bold;
    height: 20px;
    padding-top: 12px;
    padding-bottom: 2px;
    padding-right: 11px;

    }
    .psycho{
    background-color: #733273;
    background-image: url("../images/psych/home_titlebar.gif");
    background-repeat: no-repeat;

    }

    Using float:left; allows the four columns to fill the available space. Subtracting the left hand column, which has a width of 255, we have 535 pixels. This allows for 3x170 pixel columns and padding of 25 pixels – exactly correct.
    The three columns of  

    are easy enough to create once the width and padding is calculated. In my first draft the base of each column (on the Y coordinate) ended in a different place – giving a ragged appearance. Getting all three columns to end in the same place on the y coordinate is far more complicated. Such columns are known as ‘stretch columns. This is something that I will cover later.

     

    The final area of the screen is bottomnav

    . When putting this together I used much the same technique as I did with contentcols. Only here there are two rows of three columns each. These areas don’t quite work if you enlarge the text size – and that is something I could further improve.
    My version one page can be found at http://www.lsbu.ac.uk/ahs/index_v1.shtml
    note that the problems with the ‘top bar’ are the result of subsequent stylesheet refinement.

     

    Refining styles on the page

    Now that the basic work of dividing up the page is done, it is necessary to perfect and tweak the style sheet to:

    • Solve minor stylistic problems
    • work on all browsers

    Stretch columns

    One of the issues mentioned above was producing three columns each of which finishes at the same point on the vertical axis, rather than the columns having a ‘ragged’ appearance see http://www.lsbu.ac.uk/ahs/index_v1.shtml.
    This is one of the key teasers with CSS and you will discover that there is not a fully satisfactory solution (place ‘css stretch column’ into Google).
    The method I adopted and indeed the most common solution is to add another wrapping layer around the three columns that need to ‘stretch’.
    This wrapping layer has a background image which is the colour of the three columns.
     

    This layer has a background image with 3 columns to provide a background for the nested layers

     See illustration below:
    stretch columns 

     

     

     

     


     


    Box model hack

    It should not be necessary to use CSS filters (css style sheets with definitions for different browsers) or CSS hacks – IN A PERFECT WORLD.
    Unfortunately the world is not perfect, and in order to get your stylesheet to work under IE5.0 or IE5.5 you will need to know about the box model hack. Luckily for everybody these browsers are fast disappearing from view.
    The problem really is that early versions of Internet explorer defined a ‘box’ in a different way from modern browsers.
    IE5 says that the width element of a box is the total width including padding, borders and margins. IE6 and Firefox reckon that a box width is a measurement of the inner part of the box prior to padding and margins being added.
    It is possible to add some CSS commands telling browsers to measure a box to the outside rather than the inside, but this is not the preferred solution. The most common solution is to create some CSS which can only be recognised by IE6.0 and Mozilla and to add a width element for these browsers which is different from the default width element.
    The CSS declaration below illustrates the point:
    #topbar{
    width:494px !important;
    width:560px;
    width/**/:/**/494px;   
    height:31px;  
    height/**/:/**/26px;    
    position:relative;
    }
    The first ‘width’ given can be read by Firefox and Opera – the priority !important tells the browser to use this width rather than any other – declared in subsequent stylesheets.
    The second ‘width’ measurement is for IE5.0 and IE5.5
    The final ‘width’ measurement is for IE6.0 – IE5.0 and IE5.5 cannot recognise this as a valid command due to the comments /**/ in the middle of the declaration.
    To find out more about the box model hack see http://www.tantek.com/CSS/Examples/boxmodelhack.html or type ‘box model hack’ into Google for a very wide range of discussions on this issue.
    Two other hacks that are worth motioning are the ‘holy hack’ which corrects problems in IE5.0 and IE5.5 by adding a height of 1% to an element.
    Another annoying problem with IE5.0 and IE5.5 is that they have problems rendering italics in a box. The lean of the letters cause the box to be expanded. The solution is to set overflow:visible for italics styled fonts! I have no idea why this works.

    Producing tweaks for various browsers is by far the most time consuming part of stylesheet work. Firefox is somewhat more reliable that Internet Explorer when it comes to interpreting style sheets but there is really not much to choose.
    There are a couple of very annoying problems that I came across when working with the AHS home page given below in no particular order:

    • the margin and padding for img varies for different browsers
    • IE adds padding on for
       
    • There is some default padding in or around images which creates very slightly different layouts from the former table layout.  To see this compare http://www.lsbu.ac.uk/ahs/index_v2.shtml with http://www.lsbu.ac.uk/ahs/index_old.shtml
      Setting margins and borders to 0 does not seem to sort this out
    • You need to recode image maps to work properly under CSS2/XHTML strict.
    • XHTML strict does not support target=”_blank” you would need JavaScript to recreate this functionality.
    • Slight differences exist between IE6.0 and Firefox when it comes to padding. These are annoying but can be overcome by using very careful measurement for the different elements. To see this look at http://www.lsbu.ac.uk/ahs/index_v2.shtml in Firefox and compare the headings with Internet Explorer.

    The final corrected version of the AHS homepage can be viewed at
    http://www.lsbu.ac.uk/ahs/index_v2.shtml

    From this I only made one or two very minor tweaks before going live with
    http://www.lsbu.ac.uk/ahs/index.shtml

    It is worth noting that the new source code fits on 87 lines as opposed to the former code on index_old.shtml which was 276 lines.

    Forms and fieldsets

    Getting forms to work in the desired way is something I have found quite difficult to achieve in table-less layout. But using the three stage design process described above helps.
    It is also necessary to understand a few points about forms in HTML to perfect your CSS forms.
    In order that a form verifies in XHTML model you will need to include a fieldset element. Create the form using two elements for each field