Front-End

The Guide

960 Grid

Benefits of Implementing a Grid System:

  • Gives your design consistency
  • Allows flexibility between elements
  • Can make your designs more usable and legible
  • Reduces CSS coding errors
  • For the most part, it eliminates the need for nested HTML tables
  • Can be used sort of like a wireframe allowing you to plan
  • “Blesses” you with cross-browser support
  • Streamlines your development process for future projects
  • Acts as an adhesive and encourages the correlation between separate page elements
  • Makes it easier to embed images, text, and other visual aesthetics

The 960 Grid System is an effort to streamline web development workflow by providing commonly used dimensions, based on a width of 960 pixels. There are two variants: 12 (each 60 pixels wide) and 16 (each 40 pixels wide) columns, which can be used separately or in tandem. These both create 20 pixel wide gutters between columns.

There's also a 24-column option consisting of columns 30 pixels wide, with 10 pixel gutters, and a 5 pixel buffer on each side of the container.

The premise of the system is ideally suited to rapid prototyping, but works equally well when integrated into a production environment. There are printable sketch sheets, design layouts, and a CSS file that have identical measurements.

All modern monitors support at least 1024 × 768 pixel resolution. 960 is divisible by 2, 3, 4, 5, 6, 8, 10, 12, 15, 16, 20, 24, 30, 32, 40, 48, 60, 64, 80, 96, 120, 160, 192, 240, 320 and 480. This makes it a highly flexible base number to work with.

Some other commonly used grid systems are:

  • The Golden Grid, which has absolute proportions, structure on the rule of thirds, contains symmetry, asymmetry, usability, accessible typography and more!
  • The 1 KB Grid a 12 column grid system spread out over 960 pixels. Each column is 60 pixels wide with a 20 pixel gutter in between. As you would expect, there is a class that corresponds to each of the possible column widths, units 1 through 12. The HTML is as minimal as the CSS. Each column contains a class indicating its width. Columns are then contained by a row, which serves to clear the floating columns.
  • The Tripoli Framework is a a generic CSS standard for HTML rendering. By resetting and rebuilding browser standards, Tripoli forms a stable, cross-browser rendering foundation for your web projects. Tripoli doesn’t tell you how to code your web site. Instead, it forms a solid HTML rendering engine and a base for creating dynamic layouts without interfering with typographic measurements.

Absolute versus Relative URLs

Absolute URL:

Independent or free from any relationship. When you use an absolute URL, you point directly to a file. Hence, an absolute URL specifies the exact location of a file/directory on the internet. It also follows that each absolute URL is unique, which means that if two URLs are identical, they point to the same file.

Example:

<img src=“http://www.webdevelopersnotes.com/images/email.gif”/>

Relative URL:

Points to a file/directory in relation to the present file/directory. Must take into account the directory structure of the web site.

Example:

<img src=“../images/email.gif”/>

(“../” means “go up one level.”)

Which URL type is best to use — Absolute or Relative?

This is one of the most fundamental questions in web site design.

  • Relative URLs help in web site maintenance.
  • It's easy to transfer a web site from one domain name to another with Relative URLs. (If you had used absolute URLs in all links and SRC attributes, you'd have a difficult time updating each link on each page.).
  • Relative URLs are shorter than absolute URLs and hence the file size of the web page is reduced.
  • Absolute URLs too have their advantages and are especially helpful, if you want to plan to shift a page on your web site from one directory location to another. (I am not sure why you would want to do this, but if you do, absolute URLs would be helpful in such cases.).

Character Encoding

Using proper encoding is all about usability, both for the publishers of the website and for the viewers of its content. Finding the proper encoding is typically easy, but when working with multilingual sites, or extensive typography, it's a must to learn how to use it correctly.

At a technical level, character encoding is the way characters (letters, numbers, symbols) are represented in numerical values that a computer can understand. When we save an HTML document, it is saved with a certain character encoding. As web developers, our job is to declare what character encoding is being used so the browser knows, and can interpret it as such.

Replacing a few characters needed with ASCII rather than upgrading the character encoding used is the more efficient way of doing things. You can then place the keyword or numbers between an ampersand and semicolon and the browser will understand that it needs to interpret it into one single character or symbol.

Most of the worry or character encoding may come only for non-English websites. Yet, the character encoding may want to be changed for typographical reasons. Especially curly quotes, commas, apostrophes, and other correct typographical elements may be wanted, for design purposes primarily. Otherwise, if certain math symbols would need to be used on an English website, this would be another reason to use a higher character encoding.

How does one choose the correct character encoding?

  • What characters will be used often? Never change the character encoding for just a few characters throughout the page, such as special symbols, spaces, or em dashes. Make this decision primarily on the language that needs to be used, and any special characters based on that.
  • Which character encodings are supported by many browsers? Some browsers cannot read certain encodings, either because they are older, or do not have add-ons or settings required to view certain encodings. As a best practice, use common encodings that are supported widely across browsers.
  • What are the limitations of my webpage editor? Can it save correctly in the character encoding you've specified? There's not a whole lot to worry about here, as most editors can handle a wide range of character encodings, but just be wary of this issue, and try to stick to the more common character encodings.

Implementing (3 options):

  1. Adding a character encoding to a webpage is as easy as including a meta tag for it: <meta http-equiv=“Content-Type” content=“text/html; charset=ISO-8859-1” />. The character encoding is defined by the charset attribute. The character encoding for the example above is “ISO-8859-1”.
  2. Declaring character encoding in an XML/XHTML document like so: <?xml version=“1.0” encoding=“utf-8” ?>.
  3. With access to the FTP and server, it can be sent as a site-wide header: Content-Type: text/html; charset=utf-8

Click here for a list of all the common character encodings.

CSS Box Model

Every element in web design is a rectangular box that has a width & height, then padding, then a border and lastly margin, which is the only property that does not affect the size of the box — it affects surrounding content that's interacting with the box. When calculating the actual size of the box, you must take into account (i.e. add up the values of) all the properties (except the margin).

Boxes As Block-Level Elements (Defaults):

  • Padding/Borders: zero if you used a CSS Reset or the browser default, which usually isn't zero.
  • Width of Static/Relatively Positioned Box: if it's undeclared and width is 100% & padding/border push inwards. In other words, the default width of a box isn't really 100% but more “whatever is left” whereas a when box width is declared 100%, its padding/border push outwards.
  • Width of Absolute Positioned & Floated Boxes: if it's undeclared, width is only as wide as it needs to be to hold the content (i.e. it expands horizontally) and wraps only when it reaches 100% of the parent's width. BE CAREFUL WITH THESE.

Boxes As Inline Elements:

  • Inline elements are boxes that really long and skinny rectangles, that wrap at every line. They are able to have margin, padding, borders just like any other box.
  • If there's a left margin, it pushes only the first line of the box (i.e. the beginning of the box) to the right. Padding is applied above and below the line, and when it wraps it ignores the line above its padding and begins where the line-height dictates it should begin.

CSS3 Measurement Units

In terms of lengths, there are both relative and absolute lengths:

  • em: relative to the font size of the parent element
  • ex: relative to the height of the lowercase ‘x’
  • gd: used in East Asian typography, not relevant to us
  • rem: relative to the root font size
  • vw: relative to the viewport width: the viewport with is 100vw
  • vh: relative to the viewport height: the viewport height is 100vh
  • vm: relative to viewport width or height, whichever is smaller
  • ch: relative to the size of the 0 (zero)
  • px: relative the screen resolution not the viewport size, : generally 1point, or 1/72 or an inch
  • in: an inch
  • cm: a centimeter
  • mm: millimeter
  • pt: point is 1/72 of an inch
  • pc: pica, or 1/12 of a point
  • %: relative to the parent element, it’s normally defined self or other element defined by the property.

The most common value types in CSS include pixels and percents.

Pixels can be considered both a relative and absolute. Pixels are a relative measurement because the measurement is based on the screen resolution of the monitor or screen, rather than the viewport size. However, pixels are also an absolute size because lengths given in pixels are immutable: they can only be increased via zoom features.

Images, such as jpeg photos and gifs have an absolute width and height, defined in pixels. Increasing or decreasing the size of these image types with CSS or via the width and height attributes of the image tag distort the image.

With some of the new CSS3, such as transforms and animations, length units do not suffice. We also need to learn and understand angles, times and frequencies. These measurements have been around and used in aural (or spoken) style sheets, but now with browser support for transitions, transforms and animations, angles and times have become relevant to the screen as well. The default unit for all of the length, angle, time and frequency values is zero, and all the values are interpreted as floats.

  • deg: degrees (angles). Degrees range from 0 to 360deg, with those two being equal. Positive degrees go clockwise, negative degrees go counter clock wise. For example, -90deg is one quarter of the way around counter clock-wise, turning it on its left side. 90deg will turn it clockwise 90 degrees.

Example:

.image1 {

      -webkit-transform: rotate(-5deg);

      -moz-transform: rotate(-5deg);

      -o-transform: rotate(-5deg);

      transform: rotate(-5deg); 

}

  • grad: gradians (angles). A grad, or gradian, is equivalent to 1⁄400 of a full circle. Similar to degrees, a positive grad value will go clockwise, a negative value goes counter clockwise 100grad will be at a 90% angle.
  • rad: radians (angles). A rad, or radian, is equal to 180/π degrees, or about 57.3 degrees. An angle of 1 radian on a circumference of a circle creates an arc with an equal length to the radius of the circle. 1.570796326794897rad is the same value as 100grad and as 90deg. 90deg is the same as 100grad is the same as 1.508rad.
  • turn: turns (angles). Turns, are new in CSS3, and mean a rotation. One turn is equal to 360deg. For example, 2turn = 720deg. Note that turn is singular, and there is no space between the number and its unit. Rotate(900deg) is equivalent to rotate(2.5turn).
  • ms: milliseconds (times).
  • s: seconds (times). There are 1,000 milliseconds in a second. The format of a time value is a number followed by ‘s’ for seconds or ‘ms’ for milliseconds. 0.5s = 500ms
  • Hz: Hertz (frequencies).
  • kHz (case-insensitive): kilohertz (frequencies). Frequency values are used with aural (or spoken) cascading style sheets. 1,000Hz = 1kHz. Frequencies can be used to change the pitch of a voice reading text. A low frequency is a bass sound, a high frequency is a treble.

Example (low-pitched voice):

p.low { pitch: 105Hz; }

q.squeal { pitch: 135Hz; }

CSS Positioning

There are five CSS position properties: static, relative, absolute, fixed, and inherit.

Static Positioning

If position: static; in your CSS on multiple elements, they will stack one on top of the other like so. Use static positioning for simple, single-column layouts where each element must sit on top of the next one. There are no shifting/offsetting capabilities available with static positioning (static positioning will ignore top, right, bottom and left properties). If you don't set the position of your element, static is the default.

Relative Positioning

Relative positioning is like static positioning in that elements will play nicely with each other and stack nicely, but with super powers. A relatively positioned element can be offset (top, right, bottom, left):

position: relative;

left: 200px;

The magic is that when you use the offset property to shift a relatively positioned element, it doesn’t affect the element(s) that follow. Subsequent elements are still positioned as if the relatively positioned element is in its non-offset position like so.

Another bonus of relative positioning is creating a coordinate system (or reference point) for child elements. When an element is placed within another element in HTML…

<div id=“box_1”>

      <div id=“box_2”>…</div>

</div>

…and given relative positioning in CSS…

#box_2 {

      position: relative;

      left: 200px;

      width: 200px;

      height: 200px;

      background: #44accf;

}

…that element now positions itself relative to its parent's coordinate system (i.e. x-y values) like so.

Absolute Positioning

With absolute positioning, the element is removed from the normal flow. Put it anywhere and it won’t affect or be affected by any other element in the flow. Imagine that it has velcro on its back — tell it where to stick and it sticks. Absolutely positioned elements can be offset (top, right, bottom, left) like so…

position: absolute;

top: 0;

left: 0;

position: absolute;

top: 0;

right: 0;

position: absolute;

bottom: 0;

left: 0;

position: absolute;

bottom: 0;

right: 0;

…to garner this four-corners effect.

Like relatively positioned elements, absolute elements also create a new coordinate system for child. And they scroll with the document.

Fixed Positioning

An element with fixed positioning shares all the rules of an absolutely positioned element, except that the browser positions the fixed element, as opposed to any parent element. And fixed elements don't scroll with the document. Support in older browsers isn't reliable. Here are some old IE fixes.

Inherit Positioning

Inherit positioning is where the element inherits the value of its parent element. Typically, position property elements do not naturally inherit their parent’s values — the static value is assigned if no position value is given. You can type inherit or the parent element’s value and get the same result.

CSS Sprites

CSS sprites replace old-school image slicing and dicing (and the necessary JavaScript) with a CSS solution. By building a grid of images and devising a way to get each individual cell out of the grid, you can store all buttons/navigation items/etc in a single master image file, along with the associated “before” and “after” link states.

You move an “after” image in the place of the “before” image (through CSS positioning) instead of replacing one with the other. The result makes no real visual difference except this method avoids the “flicker” effect that you don’t want.

You start with a clean block of HTML code such as:

<ul id=“skyline”>

      <li id=“panel1b”><a href=“#1”></a></li>

      <li id=“panel2b”><a href=“#2”></a></li>

      <li id=“panel3b”><a href=“#3”></a></li>

      <li id=“panel4b”><a href=“#4”></a></li>

</ul>

And add this CSS:

#skyline {

      width: 400px;

      height: 200px;

      background: url(test-3.jpg);

      margin: 10px auto;

      padding: 0;

      position: relative;

}

#skyline li {

      margin: 0;

      padding: 0;

      list-style: none;

      position: absolute;

      top: 0;

}

#skyline li, #skyline a {

      height: 200px;

      display: block;

}

You don't assign the before image to the links. It’s applied to the <ul> instead. You leave the links themselves as empty, transparent blocks (though with specific dimensions) to trigger the link activity, and position them using the containing <li>s. If you position the links themselves and ignore the <li>s, you’d start seeing errors in older browsers, so avoid this.

If you absolutely position the <li>s, which are descendent elements, they'll base their absolute position not off the corners of the browser window, but off the corners of the nearest positioned ancestor element. When you apply position: relative; to #skyline, you can absolutely position the <li>s from the top left corner of #skyline itself.

#panel1b { left: 0; width: 95px; }

#panel2b { left: 96px; width: 75px; }

#panel3b { left: 172px; width: 110px; }

#panel4b { left: 283px; width: 117px; }

In the past you would have had to apply JavaScript to swap in a new image for the “after” state. But now the “after” states are in one image, so all you need to do is selectively pull each state out for the appropriate link by moving the position of the image through CSS. A little math enables you to offset the background image vertically and horizontally so that only the piece containing the “after” state shows:

#panel1b a:hover {

      background: transparent url(test-3.jpg)

      0 -200px no-repeat;

}

#panel2b a:hover {

      background: transparent url(test-3.jpg)

      -96px -200px no-repeat;

}

#panel3b a:hover {

      background: transparent url(test-3.jpg)

      -172px -200px no-repeat;

}

#panel4b a:hover {

      background: transparent url(test-3.jpg)

      -283px -200px no-repeat;

}

Example images: original  |  with hover

This same methodology can be applied to create stand-alone buttons and irregular shapes.

CSS Sprites work well in most modern browsers, Opera being the exception. And there are FIR issues.

Em, En & Other Characters

It has become commonplace for web developers to sacrifice many of the tools/characters associated with proper printed type because for a long time the web was void of them and now that they're available, not many know how to use them.

Enter Decimal Entity Notation, the only method of reference reliable across browsers and platforms.

Side note: UTF-8 works well but not on every browser.

Hyphens are NOT dashes

Em dash — (&#8212;)

  • An em is a unit of measurement defined as the point size of the font. 12 point type uses a 12 point em.
  • Indicates a sudden break in thought, a parenthetical statement that deserves more attention than parentheses indicate, instead of a colon or semicolon to link clauses, an open range, or vague dates.
  • A 2-em dash is used to indicate missing letters in a word.
  • A 3-em dash is used to substitute for the author’s name when a repeated series of works are presented in a bibliography, as well as to indicate an entire missing word in the text.

Examples:

I was thinking about writing a—what time did you say the movie started?

Peter Sheerin [1969—] authored this document.

I just don’t f——ing care

En dash – (&#8211;)

  • An en is one-half of an em.
  • Indicates a range of numbers, hyphenates compounds of compounds when at least one pair is already hyphenated, joint authors and all caps text. An en is also used instead of the word “to” or a hyphen to indicate a connection between things

Examples:

Netscape 6.1 is an Open-Source–based browser

Bose–Einstein

Hyphens -

  • Use the key next to the zero on computer for hyphen only! (not minus or en)
  • Used to join compound words together.

Spaces

  • Normal/Word Space (&#32;)
  • Non-breaking space (&#160; or &nbsp;) is found in otherwise-empty table cells
  • Hair & thin spaces (&#8201;) are inaccurate
  • En space (&#8194;)
  • Em space (&#8195;)
  • Outer spaces are not defined by HTML

Quotes “ ”

  • Opening single quote (&#8216;)
  • Closing single quote (&#8217;)
  • Opening double quote (&#8220;)
  • Closing double quote (&#8221;)
  • Do not, under any circumstances, use &#147; through &#149; for curly quotes
  • Don't fake them
  • <q> and <blockquote> will auto-insert quotes but avoid until they're widely supported by browsers

Feet & Inches

  • Single prime (&#8242; not in HTML 4.01) for feet or minutes
  • Double prime (&#8243; not in HTML 4.01) for inches or seconds
  • NOT double & single quotes

Ellipsis … (&#8230;)

  • Followed by a period, an ellipsis indicates one or missing words in the sentence
  • If it indicates one or more missing sentences, then it should appear after the period of the preceding sentence, and with a space on either side.
  • If it indicates that the thought or quote is just trailing off at the end of a sentence, then only the ellipsis is used, to clarify that no words from a quotation were omitted, as would be the case if the additional period were there.

the period

The period’s official Unicode name is “full stop.”

Float Collapse

This article explains through use of illustrations that float collapsing (i.e. when elements that contain floated items don't take those floated items into account in calculating their height) sometimes produces the right layout effect such as flowing text around an image and other times yields the wrong effect. In that case, when you want the bottom of the containing element to be placed clear past the bottom of the float, a “clear” is needed.

Font Sizing

One of the most confusing aspects of CSS styling is the application of the font-size attribute for text scaling. In CSS, you’re given four different units by which you can measure the size of text as it’s displayed in the web browser. Which of these four units is best suited for the web? It’s a question that’s spawned a diverse variety of debate and criticism. Finding a definitive answer can be difficult, most likely because the question, itself, is so difficult to answer.

Scalable:

  • The “em” is a scalable unit that is used in web document media. An em is equal to the current font-size, for instance, if the font-size of the document is 12pt, 1em is equal to 12pt. Ems are scalable in nature, so 2em would equal 24pt, .5em would equal 6pt, etc. Ems are becoming increasingly popular in web documents due to scalability and their mobile-device-friendly nature.
  • The percent (“%”) unit is much like the em unit, save for a few fundamental differences. First and foremost, the current font-size is equal to 100% (i.e. 12pt = 100%). While using the percent unit, your text remains fully scalable for mobile devices and for accessibility.

Fixed-Size:

  • Pixels (“px”) are fixed-size units that are used in screen media (i.e. to be read on the computer screen). One pixel is equal to one dot on the computer screen (the smallest division of your screen’s resolution). Many web designers use pixel units in web documents in order to produce a pixel-perfect representation of their site as it is rendered in the browser. One problem with the pixel unit is that it does not scale upward for visually-impaired readers or downward to fit mobile devices. Pixels are considered acceptable font size units (users can use the browser’s zoom feature to read smaller text), although they are starting to cause some issues as a result of mobile devices with very high density screens (some Android and iPhone devices have upwards of 200 to 300 pixels per inch, making your 11- and 12-pixel fonts very difficult to see!).
  • Points (“pt”) are traditionally used in print media (anything that is to be printed on paper, etc.). One point is equal to 1/72 of an inch. Points are much like pixels, in that they are fixed-size units and cannot scale in size.

Generally, 1em = 12pt = 16px = 100%

When using these font-sizes and you increase the base font size (using the body CSS selector) from 100% to 120%, both the em and percent units get larger as the base font-size increases, but pixels and points do not. It can be easy to set an absolute size for your text, but it’s much easier on your visitors to use scalable text that can display on any device or any machine. For this reason, the em and percent units are preferred for web document text.

In the example above, we used the percent unit as our base font-size (on the body tag). If you change your base font-size from percent to ems (i.e. body { font-size: 1em; }), you probably won’t notice a difference. BUT when “1em” is our body font-size and the client changes the “Text Size” setting of their browser (this is available in some browsers, such as Internet Explorer) to either “Smallest” or “Largest”, the em text scales too abruptly — the smallest text becomes hardly legible on some client machines — while percent text scales at a reasonable rate, allowing designers to preserve readability, accessibility, and visual design.

Design Standard:

Use percent on the body element (body { font-size: 62.5%; }), and then use the em unit to size it from there. As long as the body is set using the percent unit, you may choose to use either percent or ems on any other CSS rules and selectors and still retain the benefits of using percent as your base font size.

Front-End Development Best Practices

Top 10 best practices for producing a clean, semantic, cross-browser code:

1. Explain which div you’re closing.

<div id=“header”>

    <div id=“sub” class=“first left”>

    </div><!-- #sub.first.left -->

</div><!-- #header -->

2. Use a CSS reset. Because by default, browsers don’t apply the same default styling to HTML elements, a CSS reset will ensure that all element have no particular style so you can define your own without the risk of many cross-browser rendering issues.

3. Don’t use @import. CSS files can be included using the @import directive, BUT it's much slower than the other way to include stylesheets into a html document:

<link rel=‘stylesheet’ type=‘text/css’ href=‘a.css’>

4. “Smush” your images. “Save for web devices” in Photoshop can yield optimized images that are still too big, especially when a site's bandwidth is a consideration. There's a cool tool called Smush It. You enter your unoptimized image url, and Smush It will create a perfectly optimized image for you. You can save up to 70% of the file size, while keeping the original quality.

5. Don’t mix CSS with HTML. HTML defines the content. CSS describes the content. They should be kept separate. The “style” attribute allows developers to insert CSS directly into a html document. This is very useful for testing or when you’re in a hurry. But the style attribute is bad practice, that goes completely against the CSS philosophy.

6. Don’t mix Javascript with HTML. Just like mixing your HTML code with CSS is bad practice, you shouldn’t use any Javascript in your html documents. It's best practices to keep your HTML document clean.

7. Use conditional comments. To target specific versions of IE, you can use the well known IE hacks, as shown below:

height: 200px; /* normal browsers */

_height: 300px; /* IE6 */

.height: 250px; /* IE7 */

*height: 350px; /* All IEs */

Those hacks are extremely useful sometimes, but they are not the best way to target a specific version of IE, and it will cause your CSS validation to fail. Instead, you should use the conditional comment shown below to target IE6, which means creating a separate/specific IE CSS file:

<link rel=‘stylesheet’ type=‘text/css’ href=‘style.css’>

<!-- [if lte IE 6]>

<link rel=‘stylesheet’ type=‘text/css’ href=‘ie.css’>

<![endif]-->

8. Place Javascript file at the bottom. A popular practice of the late 90′s/early 2000′s was to place Javascript files within the <head> and </head> tags. The problem is that your javascript files will be loaded first, and consequently your content will be loaded after. By placing Javascript files at the bottom of your documents, you’ll ensure that JS files will be loaded only when the content has been properly displayed.

      <script type=‘text/javascript’ src=‘jquery.js?ver=1.3.2’>…</script>

   </body>

</html>

9. Use HTML semantically. HTML is not a programming language. It is a markup language, used to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, and more. It is important to use HTML elements semantically. As an example, a navigation menu should always be an unordered list.

10. Test WHILE you build to avoid cross-browser issues. “One of the biggest mistake I ever made when developing html, CSS, and javascript, was not to test my pages on multiple browser while I was writing them. Instead, I used to write all my code and just view in Firefox to see how it was rendered.” In theory, this should be good. But as you know, cross-browser issues are a major problem for front-end developers, especially due to IE. *** If you test your documents on Firefox/IE/Chrome while your writing it, cross-browser rendering problems will be much easier to fix. *** Use this very handy tool to test on multiple versions of IE.

i,b,em & strong elements

Several historically presentational HTML elements have been given semantic meanings in HTML5.

<i> and <b> were HTML4 font style elements and are still used presentationally where appropriate to follow typographic conventions. They now have semantic meaning and their style can be changed via CSS, meaning they’re not only presentational. In other words, <b> doesn’t have to be bold. Because of this, it’s recommended to use classes to indicate meaning to make it easy to change the style later.

The <i> element represents a span of text in an alternate voice or mood.

Or otherwise offset from the normal prose (content whose typical typographic presentation is italicized). Only use <i> when nothing more suitable is available. For example:

  • <em> for emphasized text or text with stress emphasis
  • <strong> for text with semantic importance
  • <cite> for titles in a citation or bibliography
  • <dfn> for defining a word
  • <var> for mathematical variables

Use CSS instead for italicizing blocks of text, such as asides, verse, and block quotations. Remember to use the class attribute to identify why the element is being used, making it easy to restyle a particular use. You can target lang in CSS using the attribute selector (eg: [lang=“ja-latn”]).

Things that are typically italicized include foreign words (using the attribute lang=“”), taxonomic and technical terms, ship names, inline stage directions in a script, some musical notation, and when representing thoughts or hand-written text inline.

Examples:

<i class=“voiceover”> to indicate a voiceover (alternate mood)

<i class=“taxonomy”> for taxonomic names

The <b> element represents a span of text offset from its surrounding content without conveying any extra importance

Such as keywords in a document abstract, product names in a review, or other spans of text whose typical typographic presentation is bold text. Only use <b> when nothing more suitable is available. For example:

  • <em> for emphasized text or text with stress emphasis
  • <strong> for text with semantic importance
  • <h1> – <h6> for titles
  • <mark> for highlighted or marked text

Use classes on list items for a tag cloud. To recreate traditional typographic effects, use CSS pseudo-element selectors like :first-letter, :first-line and :first-of-type where appropriate. Again, remember to use the class attribute to identify why the element is being used, making it easy to restyle a particular use.

For <b> text that should merely look different, there is no requirement to use font-style: bold. Other styling could include a round-cornered background, larger font size, different color, or formatting such as small caps.

<em> now represents stress emphasis or a span of text with emphatic stress that is linguistic.

It's something you’d pronounce differently that can change the nuance of a sentence.

<strong> now represents a span of text with strong importance.

Indicate relative importance by nesting <strong> elements, and use <em> for text with stress emphasis, or <b> for text that is “stylistically offset” or bold without being more important.

Page Flow

Page flow or “the flow,” as it is referred to in this article, is the most basic HTML layout and it operates on every HTML page. Normally flowed page elements are by default statically positioned. When an element is described as having static positioning, it's usually thought of as being “unpositioned.” All flowed elements are by default statically positioned but they can also be positioned as relative.

Page flow entails two kinds of flow: block and inline. According to CSS specs, both element types may be assigned a position value, but in practice it's best not to try positioning inline elements due to inconsistent behavior in IE.

Block Flow:

All block elements are by default just as wide as the container surrounding them, and they always stack up vertically, one atop another, unless you alter the arrangement by forcing them out of their normal locations. Block elements include paragraphs, divs, lists, and a number of others.

Tables are an exception, in that they do stack vertically but don't automatically widen to fill a containing element. Instead they “shrink-to-fit” around their internal content, so if you want them to act like other block elements you must assign them a width of 100%. Be careful because in that case any side borders or paddings will be added to that 100% width, unlike natural block elements which have a default width of “auto“.

Inline Flow:

While all block elements start on a new line, inline elements usually stay on the same line as any inline elements that directly precede them. Most inline elements are simple text characters, but many actual tagged elements (<img>, <span>, <em>, etc) are also inline.

Inline elements stack sideways, starting from the left and extending to the right as each new inline element is read by the browser. When the available horizontal space within the containing element is no longer wide enough to hold the next inline element, that element is dropped to a new line and moved to the far left end of the containing block, repeating the process. Be aware that some languages are read right-to-left, and CSS does have special properties to reverse the normal LTR inline flow direction to RTL for those cases.

When a browser runs out of inline elements for a given line, or when it needs to make a new line, the heights of all the elements in the line being formed are measured. Then a “line box” is created that is the same height as the tallest measured element, and the line box is wrapped around them all.

Each time the browser creates a line box it is added below the previous one, so line boxes behave much like block elements, although some of the properties governing them are different. For instance, a text character in a line box does not sit on the bottom of the line box, but instead on something called the baseline which is usually a few pixels above the bottom of the line box. This way characters with “descenders“ (like the hook on the bottom of a small “g“) have room for those descenders to hang down while allowing the main bodies of the characters to remain aligned.

Noteworthy:

You cannot specifically create a line box; they are strictly for use by the browser in organizing groups of inline elements.

Block elements may contain both inline elements and other block elements, but inline elements may contain only other inline elements. It's illegal to place a block element inside an inline element like this: <span><div>…</div></span>

The CSS display property allows you to change a block element into an inline one and vice versa. This can be very useful, but be aware that while making a paragraph inline does cause it to act like a span, it doesn't make it legal to place that paragraph inside a span! You could get away with it in modern browsers but it won't validate. The display property accepts several other values besides “block“ and “inline“, and a particularly useful value is “none“, often used to temporarily hide elements on a page, to be revealed later.

Block boxes are always rectangles and can be given widths and heights, but inline elements ignore those properties, since they must occupy an unknown set of line boxes. Both block and inline elements can have padding and margins, but using these on inline elements might show inconsistent results across browsers, and in any case only the side paddings and margins are obeyed for inline elements.

Pseudo-Classes (:)

Pseudo-classes allow you to style content dynamically using CSS. The first set of pseudo-classes, as part of CSS1, were used to style <a> selectors :link, :visited, :hover, and :active

CSS2 introduced the :first-child and :lang() pseudo-classes:

  • :lang() There are a couple of ways to indicate the language of a document, and if you’re using HTML5, it’ll likely be by putting <html lang=“en”>> just after the doc type (specifying your local language). You can now use :lang(en) to style elements on a page, which is useful when the language changes dynamically.
  • :first-child You may have already used :first-child in your documents. It is often used to add or remove a top border on the first element in a list. Strange, then, that it wasn’t accompanied by :last-child; we had to wait until CSS3.

CSS3 introduced 16 new pseudo-classes as part of the W3C’s CSS Proposed Recommendation, and they are broken down into four groups:

1. Structural pseudo-classes:

Selectors that have been turbo-charged to dynamically select content based on its position in the document.

The :root pseudo-class selects the root element on the page. Ninety-nine times out of a hundred, this will be the <html> element.

:nth-child() is useful when displaying data that consists of rows or columns and you want to include/exclude certain styles on certain elements. Examples: ul li:nth-child(odd or even), li:nth-child(3), li:nth-child(2n), li:nth-child(4n + 1), etc.

:nth-last-child(n) operates much like :nth-child() except in reverse, counting from the last item in the selection.

:nth-of-type(n) and :nth-last-of-type(n) get even more specific and apply styles only to particular types of element.

A useful CSS3 structural pseudo-class selector tester.

Here are a few others:

  • :first-of-type
  • :last-of-type
  • :only-of-type
  • :last-child
  • :only-child
  • :empty (This selects only elements that have no children and no content. Again, this might be useful when dealing with dynamic content outputted from a database.)

2. Target pseudo-classes:

:target allows us to style elements on the page based on the URL. If the URL has an identifier (that follows an #), then the :target pseudo-class will style the element that shares the ID with the identifier.

3. Pseudo-classes for the states of UI elements:

Together with :checked, :enabled and :disabled make up the three pseudo-classes for UI element states. That is, they allow you to style elements (usually form elements) based on their state. A state could be set by the user (as with :checked) or by the developer (as with :enabled and :disabled).

4. Negation pseudo-class:

:not selects everything except the element you specify, such as :not(footer).

Pseudo-Elements (::)

A pseudo-element does exactly what the word implies — it creates a phony element and inserts it before or after the content of the element that you’ve targeted. They don’t actually change anything in the document. Rather, they insert ghost-like elements that are visible to the user and that are style-able in the CSS. In other words, the (“pseudo”) content that is inserted is not visible in the page’s source (the DOM). It’s visible only in the CSS. Pseudo-elements are generally decorative or helper-like content.

They are not accessible to most assistive devices so should NEVER be used to generate content that is critical to the usability or accessibility of your pages.

The inserted element is by default an inline element. So, to give the inserted element a height, padding, margins and so forth, you’ll usually have to define it explicitly as a block-level element.

Pseudo-elements are somewhat unique because you insert the content and the styles in the same declaration block.

Inheritance: the content that’s injected will be child content in relation to the targeted element, but it will be placed “before” or “after” any other content in that element.

Syntax: you can also code pseudo-elements using the single- or the double-colon syntax (::before and ::after). There is no difference between the two syntaxes; it’s just a way to differentiate pseudo-elements (double colon) from pseudo-classes (single colon) in CSS3.

Browser Support:

  • Chrome 2+
  • Firefox 3.5+ (3.0 had partial support)
  • Safari 1.3+
  • Opera 9.2+
  • IE8+ (with some minor bugs)
  • Pretty much all mobile browsers
  • The only real problem (no surprise) is IE6 and IE7, which have no support.

Example 1

You're targeting the same element using #example:before and #example:after. Pseudo-elements must contain the content property. While the pseudo-element selector itself is needed to target the element, you won’t be able to insert anything without adding the content property. In this example, the element with the id example will have a hash symbol placed “before” its content, and a period (or full stop) placed “after” its content:

#example:before {

    content: “#”; }

#example:after {

    content: “.”;

}

Example 2

You can leave the content property empty and just treat the pseudo-element like a content-less box. However, you can’t remove the content property altogether. If you did, the pseudo-element wouldn’t work. At the very least, the content property needs empty quotes as its value.

#example:before {

    content: “”;

    display: block;

    width: 100px;

    height: 100px;

}

Example 3

You can implement a pseudo-element universally, without targeting any element. This will insert a hash symbol before the content in each element in the DOM. Even if you removed the <body> tag and all of its content, you’d still see two hash symbols on the page: one in the <html> element, and one in the <body> tag, which the browser automatically constructs.

:before {

    content: “#”;

}

Example 4

You can include a URL that points to an image, just as you would do when including a background image in the CSS. Do not use quotes here.

p:before {

    content: url(image.jpg);

}

Reset.CSS

Each browser has its own default CSS, which leads to styles you, the designer, might not want such as specific padding and margin values. It also leads to styling inconsistencies across different browsers. That's where a CSS Reset comes in. You can “neutralize the many disparate browser defaults and establish a clean foundation for applying CSS consistently across browsers.” The next hurdle is choosing the right CSS Reset, as there are many, ranging from generic to complicated. Your design should be your guide when determining the right CSS Reset. This site lets you try all the best CSS Resets on a variety of web pages.