Pages

Labels

Powered by Blogger.
Saturday, September 8, 2012

IE and the box model


Unfortunately, older versions of Internet Explorer, along with IE 6 in quirks mode, use their own, nonstandard box model. Instead of measuring just the width of the content, these browsers take the width property as the sum of the width of the content, padding, and borders. This actually makes a lot of sense, because in the real-world boxes have a fixed size, and the padding goes on the inside. The more padding you add, the less room there will be for the content. However, despite the logic, the fact that these versions of IE disregard the specification can cause significant problems. For instance, in the previous example the total width of the box would only be 90 pixels in IE 5.x. This is because IE 5.x will consider the 5 pixels of padding on each side as part of the 70-pixel width, rather than in addition to it (see Figure 3-3).

Box model recap

The box model is one of the cornerstones of CSS and dictates how elements are displayed and, to a certain extent, how they interact with each other. Every element on the page is considered to be a rectangular box made up of the element’s content, padding, border, and margin (see Figure 3-1).

Visual Formatting Model Overview


Three of the most important CSS concepts to grasp are floating, positioning, and the box model. These concepts control the way elements are arranged and displayed on a page, forming the basis of CSS layout. If you are used to controlling layout with tables, these concepts may seem strange at first. In fact, most people will have been developing sites using CSS for some time before they fully grasp the intricacies of the  box model, the difference between absolute and relative positioning, and how floating and clearing actually work. Once you have a firm grasp of these concepts, developing sites using CSS becomes that much easier.

In this chapter you will learn about

  • The intricacies and peculiarities of the box model
  • How and why margins collapse
  • The difference between absolute and relative positioning
  • How floating and clearing work

Let's See:
Box model recap

Wednesday, September 5, 2012

Removing comments and optimizing your style sheets


Comments can increase the size of your CSS files quite considerably. Therefore, you may want to strip comments from your live style sheets. Many HTML/CSS and text editors have a search-and-replace option, making it pretty easy to remove comments from your code. Alternatively, you could use one of several online CSS optimizers such as the one found at www.cssoptimiser.com Not only does an optimizer remove comments, but it also strips out whitespace, helping to shave off a few extra bytes from your code. If you do choose to strip comments from your live style sheets, remember to retain a commented version for your production environment. The best way of managing this process is to create a deployment script that strips comments automatically when you make your changes go live. However, as this is an advanced technique, it’s probably best left to fairly large, sophisticated sites.

Instead, the best way of reducing file size would be to enable server-side compression. If you are using an Apache server, talk to your hosts about installing mod_gzip or mod_deflate. All modern browsers can handle files compressed with GZIP, and decompress them on the fly. These Apache modules will detect whether your browser  can handle such files, and if it can, send a compressed version. Server-side compression can reduce your HTML and CSS files by around 80 percent, reducing your bandwidth and making your pages much faster to download. If you don’t have access to these Apache modules, you still may be able to compress your files by following the tutorial found at http://tinyurl.com/8w9rp.

Note to self


With large, complicated projects, it is often useful to annotate your CSS files with temporary comments to aid development. These could be reminders of things you need to do before launch or look-up tables for common values such as column widths.

Structuring your code


It is a good idea to break your style sheets down into sensible chucks for ease of maintenance. At Clearleft, we usually start with the most general styles first. These include styles that are applied to the body tag and should be inherited by everything on the site. Next are any global resets we may need, followed by links, headings, and other elements.

Applying styles to your document


You can add styles directly to the head  of a document by placing them between  style tags; however, this is not a very sensible way to apply styles to a document. If you want to create another page using the same styles, you would have to duplicate the CSS on the new page. If you then wanted to change a style, you would have to do it in two places rather than one. Luckily, CSS allows us to keep all our styles in one or more external style sheets. There are two ways to attach external style sheets to a web page. You can link to them or you can import them:

Planning, organizing, and maintaining your style sheets


The larger, more complicated, and graphically rich your sites become, the harder your CSS is to manage. In this section, I will look at ways to help you manage your code, including grouping your styles into logical sections and adding comments to make your code easier to read.



Inheritance


People often confuse inheritance with the cascade. Although they seem related at first glance, the two concepts are actually quite different. Luckily, inheritance is a much easier concept to grasp. Certain properties, such as color or font size, are inherited by the descendants of the elements those styles are applied to. For instance, if you were to give the body element a text color of black, all the descendants of the body element would also have black text. The same would be true of font sizes. If you gave the body a font size of 1.4 ems, everything on the page should inherit that font size. I say  should because IE for Windows and Netscape have problems inheriting font sizes in tables. To get around this, you will either have to specify that tables should inherit font sizes or set the font size on tables separately.

Sunday, September 2, 2012

Adding a class or an ID to the body tag


One interesting way to use specificity  is to apply a class or an ID to the body tag. By doing this, you can then override styles on a page-by-page or even a site-wide basis. For instance, if you wanted all your news pages to have a specific layout, you could add a class name to the body element and use it to target your styles:

Using specificity in your style sheets


Specificity is very useful when writing CSS, as it allows you to set general styles for common elements and then override them for more specific elements. For instance, say you want most of the text on your site black, except for your  intro text, which you want gray. You could do something like this:

p {color: black;}
p.intro  {color: grey;}

This is fine for smaller sites. However, on larger sites you will find more and more exceptions will start to creep in. Maybe you want to have the introductory text on your news stories blue and the introductory text on your home page on a gray background. Each time you create a more specific style, you will probably need to override some of the general rules. This can lead to quite a bit of extra code. It can also start to get very complicated, as one element may be picking up styles from a variety of places.

To avoid too much confusion, I try to make sure my general styles are very general while my specific styles are as specific as possible and never need to be overridden. If I find that I have to override general styles several times, it’s simpler to remove the declaration that needs to be overridden from the more general rules and apply it explicitly to each element that needs it.
Friday, August 31, 2012

The cascade and specificity


With even a moderately complicated style sheet, it is likely that two or more rules will target the same element. CSS handles such conflicts through a process known as the  cascade. The cascade works by assigning an importance to each rule. Author style sheets are those written by the site developers and are considered the most important. Users can apply their own styles via the browser and these are considered the next most important. Finally, the default style sheets used by your browser or user agent are given  the least importance so you can always override them. To give users more control, they can override any rule by specifying it as !important even a rule flagged as !important by the author. This is to allow  for specific accessibility needs such as using a medium contrast user style sheet if you have a certain forms of dyslexia.

In This Section

Using specificity in your style sheets
Adding a class or an ID to the body tag

Thursday, August 30, 2012

Attribute selectors


As the name suggests, the attribute selector allows you to target an element based on the existence of an attribute or the attribute’s value. This allows you to do some very interesting and powerful things.

For example, when you hover over an element with a title attribute, most browsers will display a tooltip. You can use this behavior to expand the meaning of things such as acronyms and abbreviations:

Child and adjacent sibling selectors


The first of these advanced selectors is the child selector. Whereas a descendant selector will select all the descendants of an element, a child selector only targets the element’s immediate descendants, or children. In the following example, the list items in the outer list will be given a custom icon while list items in the nested list will remain unaffected (see Figure 2-1):

Advanced selectors


CSS 2.1 and CSS 3 have a number of other useful selectors. Unfortunately, while most modern browsers support these advanced selectors, older browsers like IE 6 do not. Luckily, CSS was created with backward compatibility in mind. If a browser doesn’t understand a selector, it ignores the whole rule. That way, you can apply stylistic and usability embellishments in more modern browsers and not worry about it causing problems  in older browsers. Just remember to avoid using these more advanced selectors for anything critical to the function or layout of your site.

The universal selector *


The universal selector is possibly one of the most powerful and least used of all the selectors. The universal selector acts like a wild card, matching all the available elements. Like wild cards in other languages, the universal selector is denoted by an asterisk. The universal selector is often used to style every element on a page. For instance, you can remove the default browser padding and margin on every element using the following rule:

* { 
  padding: 0; 
  margin: 0; 
}

When combined with other selectors, the universal selector can be used to style all the descendants of a particular element or skip a level of descendants. You will see how this can be put to practical effect a little later in this chapter.

Pseudo-classes


There are instances where you may want to style an element based on something other than the structure of the document—for instance, the state of a link or form element. This can be done using a pseudo-class selector.

/* makes all unvisited links blue */ 
a:link {color:blue;}  

/* makes all visited links green */ 
a:visited {color:green;}  

/* makes links red when hovered or activated. 
focus is added for keyboard support */ 
a:hover, a:focus, a:active {color:red;}  

/* makes table rows red when hovered over */ 
tr:hover {background-color: red;}  

/* makes input elements yellow when focus is applied */ 
input:focus {background-color:yellow;}

:link and  :visited are known as  link pseudo-classes and can only be applied to anchor elements.  :hover,  :active, and  :focus are known as  dynamic pseudo-classes and can theoretically be applied to any element. Most modern browsers support this functionality. Unsurprisingly, IE 6 only pays attention to the :active and :hover pseudo-classes when applied to an anchor link, and ignores :focus completely. IE7 supports :hover on arbitrary elements but ignores :active and :focus.

Last, it’s worth pointing out that pseudo-classes can be strung together to create more complex behaviors, such as styling the hover effect on visited links different from those on unvisited links.

/* makes all visited linkes olive on hover */ 
a:visited:hover {color:olive;}

Common selectors


The most common kinds of selectors are type and descendant selectors. Type selectors are used to target a particular type of element, such as a paragraph or a heading element. You do this by simply specifying the name of the element you wish to style. Type selectors are sometimes also referred to as element or simple selectors.

Getting Your Styles to Hit the Target


A valid and well-structured document provides the foundations to which your styles are applied. To be able to style a particular HTML element using CSS, you need to have some way of targeting that element. In CSS the part of a style rule that does this is called the selector. 

In this chapter, you will learn about:


Divs and spans


One element that can help add structure to a document is the  div element. Many people mistakenly believe that a div element has no semantic meaning. However, div actually stands for division and provides a way of dividing a document  into meaningful areas. So by wrapping your main content area in a div and giving it a class of content, you are adding structure and meaning to your document.

To keep unnecessary markup to a minimum, you should only use a  div element if there is no existing element that will do the job. For instance, if you are using a list for your main navigation, there is no need to wrap it in a div.
Wednesday, August 29, 2012

IDs or Classes?


It is often difficult to decide if an element should have an ID or class name. As a general rule, classes should be applied to conceptually similar items that could appear in multiple places on the same page, whereas IDs should be applied to unique elements. However, you then get into a debate about which elements are conceptually similar and which elements are unique.

For instance, imagine you have a site that contains primary navigation in the header, page-based navigation at the bottom of the search results page, and tertiary navigation in the footer. Do you give each of these a separate ID like main-nav, page-nav, and footer-nav, or do you give them all a class of nav and style them based on their position in the document? I used to prefer the former approach, as it felt slightly more targeted. However, it comes with its own set of problems. What happens if I decide that I now need search results navigation at the top and the bottom of the search page or that I need two levels of navigation in the footer?

Naming your elements

When naming your IDs and classes, it is important that you keep the names as “unpresentational” as possible. For instance, if you want all of your form notification messages to be red, you could give them a class of red. This is fine as long as there are no other red elements on the page. However, say you wanted to style required form labels red as well. You are now forced to guess to which element that class could refer, and things are already starting to get confusing. Imagine how confusing the code could become if you used presentational elements across the whole site? This gets even more complicated if you decide to change the presentation of your form notifications from red to yellow. Now, you either have to go back and change all your class names, or you have an element called red that looks yellow.

IDs and class names


Meaningful elements provide an excellent foundation, but the list of available elements isn’t exhaustive. HTML 4 was created as a simple document markup language rather than an interface language. Because of this, dedicated elements for things such as content areas or navigation bars just don’t exist. You could create your own elements using XML, but for reasons too complicated to go into, it’s not very practical.

HTML 5 hopes to solve some of these problems by providing developers with a richer set of elements to work with. These include structural elements like header, nav, article, section, and footer as well as well as new UI features like data inputs and the menu element. In preparation for HTML 5, many developers have started adopting these as naming conventions for their ID and class names.

The power of meaning

Meaningful markup provides the developer with several important benefits. Meaningful pages are much easier to work with than presentational ones. For example, say you need to change a quotation on a page. If the quotation is marked up correctly, it is easy to scan through the code until you find the first blockquote element. However, if the quotation is just another paragraph element, it will be a lot harder to find. For a more complicated, but no less realistic example, say that you needed to add an extra column to your homepage. You could simply drop the content in at the right point and then update the widths in your CSS. To do the same in a table-based layout you’d need to add an extra column in your table, change the colspan settings, alter the widths on all the cells, and change the widths of all your shim gifs. In effect, you’d have to change the entire structure of your page to accommodate this simple change.

A brief history of markup

The early Web was little more than a series of interlinked research documents using HTML to add basic formatting and structure. However, as the World Wide Web gained in popularity, HTML started being used for presentational purposes. Instead of using heading elements for page headlines, people would use a combination of font and bold tags to create the visual effect they wanted. Tables got co-opted as a layout tool rather than a way of displaying data, and people would use blockquote to add whitespace rather than to indicate quotations. Very quickly, the Web lost its meaning and became a jumble of font and table tags. Web designers came up with a name for this kind of markup; they called it tag soup (see Figure below).