Watkins Web 3: Blog

Posts tagged with “css”

Intro to Webfonts

The font stack

Traditional CSS font stacks work by accessing fonts (by name) that are installed on the user’s computer. If the font at the beginning of the stack isn’t installed, the browser will try to use the next font in the stack that is available. Remember to end your stacks with a generic keyword like serif, sans-serif, or monospace.

body  {
	font-family: georgia, serif;
h1, h2, p {
	font-family: "Helvetica Neue", helvetica, arial, sans-serif;
code {
	font-family: "Courier New", courier, monospace;

A quick note: very few fonts common to most computers are optimized for screen display, and you should be particularly careful about the scale at which you set them. For instance, Bodoni and Baskerville have very thin strokes designed for print resolution; even the advanced anti-aliasing used by Mac OS X and Windows 7 won’t produce a good result if you set these fonts at 10px.

Cheat sheet: Verdana and Georgia are probably the best fonts that are both common to most Mac and Windows machines and are designed for screen. Thank you, Matthew Carter. Some would add Lucida Grande (or Lucida Console on Windows) to this list, but it doesn’t have real italics.

Here’s the comparison of commonly-used fonts I showed in class.


In the past two and half years, webfonts — that is, font files served from the server and loaded by the browser for a particular website — have gone from theory to reality. The major reasons have more to do with licensing deals than technological progress, but in any case, all the major browsers now support webfonts, though not all the same format. (All the good browsers use the emerging .woff file format, while IE requires a .eot file.)

Depending on licensing and the font vendor, you may end up hosting the font files on your own server or you may link to a font service’s CSS file or Javascript. (All webfont services/foundries will have instructions on how to do this embedding.) Once this basic embedding is done, you can then use straightforward CSS font stacks to assign elements your font choices. Note that good fonts have separate font files for bold and italic, so you may have to do this kind of thing to access the proper files:

body  {
	font-family: "FranklinGothic", arial, sans-serif;
body strong {
	font-family: "FranklinGothic-Bold", arial, sans-serif;
	font-weight: normal; /* prevent double-bolding */
body em {
	font-family: "FranklinGothic-Italic", arial, sans-serif;
	font-style:normal; /* prevent double-italicization */

Note that this makes fallbacks problematic, since if our webfont fails we can’t specifically fall back to an italic version of Arial.

The precise typographic results you get from a webfont — especially as regards anti-aliasing (blurriness) — can vary greatly depending on the care with which the service has constructed the webfont file. The web is filled with complaints about hastily converted fonts that show poor “hinting,” which is the process by which fonts should be customized to anti-alias well. The upshot: don’t buy a webfont from just anyone — use a respected service or foundry that has shown a commitment to quality.

Here are some of the higher quality places to start if you’re interested in using webfonts on a project:

  • Typekit (some free fonts, but primarily an annual subscription service)
  • Myfonts (primarily one-time-purchase, self-hosted webfonts)
  • Typotheque (small Dutch type foundry and webfont service, available as one-time purchases)
  • Webtype (both subscription and self-hosted)
  • Google Fonts (free fonts of mixed quality)

In related news, Hoefler & Frere-Jones are supposedly launching their own webfont service sometime soon. At the moment they have two beta-testers: Jason Kottke and Barack Obama.

Further Reading


This is pretty cool: Pea.rs is a set of “design patterns” with sample HTML and CSS for you to borrow. So if you’re making a thumbnail grid or other common design element, take a look here to see if it will speed up your process.

The whole site is a Wordpress theme, so you could take it and construct your own set of design patterns that you use often or want to share.

CSS selecting: nth-child()

Found this other CSS selector for targeting children. It's called nth-child() and it's pretty cool. Inside the parenthesis you can put a 2 or 3 or whatever you like. To target the child. Also, some mathematical formulas can go inside the parenthesis for targeting multiple children. nth-child(3n+0) would target children that are a multiple of 3. Even using nth-child(odd) and nth-child(even) works. Just thought that was pretty interesting and handy.

CSS: nth-child()

Cheat Sheet: CSS Positioning

The position property is powerful but can be problematic when used incorrectly. If you’re just trying to create columns for your content or put an image over to one side, you should use CSS floats, not positioning.

But for certain situations, position:absolute, position:relative, and position:fixed are necessary. Here’s a rundown.


Keep in mind that the default state of HTML elements in “normal flow” is position:static;. “Static” is a bit of a deceptive word: it just means that the element naturally takes up space on the page and pushes other elements down (or to the side, if floated) by as much space as it occupies.

When you target an element in CSS and apply position:absolute, a few things happen:

  1. The positioned element is removed from “normal flow”
  2. The positioned element can be moved with the top / bottom and left / right properties, in addition to margins and padding
  3. The other elements on the page no longer “know” the dimensions or location of the positioned element. In fact, they flow down the page as if the element weren’t there at all.

Naturally, this makes position: absolute; useful for making some content overlap other content.

position: relative

Position:relative positions an element “relative” to where it would have been positioned statically. In other words, rather than add a margin-left:20px;, you could use position:relative; left: 20px;.

This is a contrived example, though, and we tend to use position:relative for a totally different purpose: By default, position:absolute’s coordinates are determined by the closest positioned container. This is usually the browser window itself (<body>). Since we often want to use a different container’s coordinates for absolute positioning, we can apply position:relative to the container of our choosing. Without a top or left value, this doesn’t do anything to the container itself. Instead, it allows us to apply position:absolute; to some nested element or elements and have our coordinates be relative to the container.

For example, some HTML:

<div id="main-column">
	<ul id="nav">
		[navigation links]

And the CSS:

#main-column {
	width:500px;       /* set a width */
	margin:0 auto;     /* and center it on the page */
	position:relative; /* reset positioning coordinates for elements inside #main-column */
#nav {
	position:absolute; /* remove from document flow */
	right:20px;        /* this means 20px from the right edge of #main-column */
	top:20px;          /* this means 20px from the top edge of #main-column */


Like position:absolute;, position:fixed; pulls the content out of normal document flow. In addition, it locks its position (defined by top / bottom and left / right) relative to the browser frame, so the element stays on screen even as the user scrolls.

If you need to apply position:fixed relative to a container, apply position:absolute; to the container first.

Cheat Sheet: CSS Floats

Floats are a useful but tricky tool for altering what we call the “normal flow” of an HTML document. Remember the chief characteristics of normal flow: elements marked up with inline HTML tags (a, strong, em, img) march across the screen as if they were running text, falling to the next line only when they run out of horizontal sapce, whereas block level elements (p, h1, h2, ul, table) start on a new line occupy their own horizontal space.

Float Basics

Sample Image The simplest use case for a float is for an image at the beginning of a paragraph. This paragraph shows the default, unfloated behavior: because images are inline by default, the image takes up space as if it were very large text at the beginning of the paragraph, leaving a large space to the right and above them.

Sample Image In this paragraph I’ve used the same markup, but this time I targeted the image with CSS and applied float:left; as well as a small right margin: the image stays aligned to the left of the page but the paragraph now runs around it nicely.

Notice that this new paragraph also runs around the image. Note: this is the default behavior. Neither of the paragraphs (<p>s) are themselves floated — just the image. Now for some dummy text to finish out the paragraph: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Sample Image Finally, here’s the same image at the beginning of the paragraph again, but with float:right; applied: the image goes as far as it can to the right until it hits the edge of the container, then allows content to flow around it. Now for some dummy text to finish out the paragraph: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Note: I tend to use right margins rather than left margins because I usually want the left edge of the first image (on each row) to align with its container.

Common task: Gallery

Floats come in handy when you want to create a grid of images. Use CSS to target all the images and float them all left, giving each a small right and bottom margin to separate them slightly:

Sample Image Sample Image Sample Image Sample Image Sample Image Sample Image

Common task: Columns with Opposing Floats

Floats can be applied to all sorts of elements besides images: paragraphs, list items, and of course the all-purpose block-level container <div>. When you have a design that requires column-like content areas, the technique known as “Opposing Floats” is often the most reliable. First, mark up your content however you wish and surround each content area with a div. You’ll probably want to give your divs classes or IDs (e.g. <div id="content"> and <div id="sidebar">). Now in CSS, set a width on the columns you will be floating, then float one left and the other right.

This div has been styled with width:20% and float:left;

This div has been styled with width:60% and float:right;. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

The nice part about this technique is that you don’t have to explicitly set a margin to separate the two columns: since the floats are in opposite directions, they naturally leave a space as long as their total width adds up to less than the width of their container. In addition, you don’t need to know in advance which column will end up being taller: the parent container will expand to contain them both.

Clearing Floats

Because of the default way that floats force content to wrap around them (refer to the paragraph above that begins with “notice that this new paragraph…” above), it’s common for a gallery like the one above to mess up the positioning of the heading or paragraph that follows it. Often it appears the content after the floats has been “sucked up” into the floated content.

To fix this problem, there are two possible solutions. The first is to apply clear:both; to the element that you would like to force to begin on a new line. (You could also use clear:left; or clear:right; if you only want to clear one kind and not the other.) This works pretty reliably as long as you can easily target (with CSS) the content that follows the floats in the first place.


However, when content is being inserted dynamically or in different ways on different pages, it’s not always convenient to apply clear:both; — the CSS “hook” just isn’t always available.

So some clever people figured out a way to use a CSS3 selector (:after) to insert some dummy content, clear it, and then hide it from rendering on the page. It’s a hack known as clearfix, and it enables you to clear floats by styling the container of the floats rather than the content that follows it.

The style might look like this in your CSS:

#gallery:after {             /* use :after selector to insert content after the element */
        content: ".";        /* insert a period */
        display: block;      /* set it to be a block-level element */
        height: 0;           /* make sure it doesn't actually add space to the element */
        clear: both;         /* clear the inserted period */
        visibility: hidden;  /* make sure the period doesn't show up in the document */

Using classes

Because clearing floats is such a common task, you may end up filling your CSS file with dozens of statements that clear (or clearfix) this or that element. So many people choose to cheat a bit: in CSS we create classes with the names clear and clearfix and we insert these into our HTML wherever we need to clear some floats.

The CSS looks like this:

/* Float-clearing classes */
.clear   {clear:both;}
.clearfix:after   {content: "."; display: block; height: 0; clear: both; visibility: hidden;}

And in HTML:

[a bunch of stuff involving floats]
<h2 class="clear">The next section</h2>


<div class="clearfix">
	[a bunch of stuff involving floats]
 <h2>This heading should be fine</h2>

Remember, clear:both; is for ensuring that something that comes after a bunch of floats doesn’t get pulled up into them. You apply it to the element that needs to be cleared. On the other hand, clearfix is intended for the container of floated elements, and ensures the elements that come after that container don’t get pulled up into them.

HTML5/CSS3 Which features you should and shouldn't use


HTML5 Please

Found this somewhat interesting and somewhat useful site. You can look up new features of HTML5 and CSS3 and see if they are features that are supported by a number of browsers/devices. Should you be using them now? It tells you if it's okay, good with fallbacks or polyfills or whether you should avoid using such features right now. Just a quick little reference tool. It seems as though it's still pretty new. I'm sure they'll continue adding information.

Exercise 4: Floats vs. Positioning Part 2

Exercise 4 Exercise 4 Solution View Solution

Exercise 3: Floats vs. Positioning Part 1

After you’ve done this exercise you may want to take a look at Max Design’s CSS Layouts for more examples and techniques.

Exercise 3 Exercise 3 Solution View Solution

Live HTML and CSS + livereload.js

Found this interesting video tutorial linked from nettuts. It's mostly CSS and HTML with a little javascript/jQuery. It's a good little exercise and pretty informative. It wasn't difficult to understand anything he was talking about. It has to do with creating an iframe to dynamic add CSS and HTML in the browser.

One thing that may be even more useful is to check out this livereload.js. It's a mac app. that automatically reloads everything you do with the CSS and HTML. So, you can have a window open with the page you're working on and another with a text editor and you don't have to keep moving around reloading the page to see the changes. Pretty cool!

Also worth noting the use of the HTML5 attribute contenteditable and the CSS webkit property box-sizing.

Custom CSS and HTML with iframes

Exercise 2: CSS Properties Review

As with Exercise 1, your mission is to view the enclosed screenshot, then use appropriate HTML markup and CSS to match it as closely as possible. You are allowed one class and no IDs. No floats and no position:absolute or position:relative!

Be sure to refer to the CSS Properties and Inline vs. Block cheat sheets if you need to.

Exercise 2 Exercise 2 Solution View Solution

Cheat Sheet: CSS Properties

Let’s review some of the most common CSS properties and their shorthand versions.


Fonts should be specified as a “stack” of multiple fonts: this provides fallbacks if the first font is not available to the user. Make sure to put quotation marks (single or double) around multi-word font names, and to end the font stack with an appropriate generic keyword (serif, sans-serif, monospace). If you put the page’s primary font on the body tag, nested elements like paragraphs, lists, etc. will inherit the font without you having to specific it again:

body {font-family:"Helvetica Neue", helvetica, arial, sans-serif;}
body blockquote {font-family:georgia, "Times New Roman", times, serif;}
body code {font-family: monospace;} /* code samples on this site use this rule along with background-color:yellow; */

Set type size and leading:

body p {font-size:12px; line-height:15px;}

You’re welcome to use the shorthand font property, but it’s fairly picky about the minimum properties:

body p {font: 12px georgia, "Times New Roman", times, serif; } /*  "font size font-family" is the fewest properties you can declare with the font shorthand; otherwise the whole line gets ignored */

We probably also want to specify a line-height; to do that, use a slash after the font-size and put your line-height there:

body p {font: 12px/15px georgia, "Times New Roman", times, serif;}

If you want to add all the other possible options, they need to come before the mandatory settings:

body p {font: italic small-caps bold 12px/15px georgia, "Times New Roman", times, serif; } /* all the fixins: font-style, font-variant, font-weight, font-size, line-height, font-family */

Some other typographic properties:

p em {font-style:italic;} /* a little redundant: browsers tend to italicize the emphasis tag by themselves */
p strong {font-weight:bold;} /* a little redundant: browsers tend to bold the strong tag by themselves */
span.caps {text-transform:uppercase; letter-spacing:1px; } /* better method for small-caps than using font-variant:small-caps */

Don’t forget you can use the normal value to override previous bold/italic settings (or the defaults):

p strong {font-weigh:normal; color:red;} /* in this design a color change stands in for bold */

Realign the text of an element (only works on block-level elements):

h2 {text-align: center;}
p.caption {text-align:right;}

Indent the first line of an element:

article p {text-indent:20px; margin:0;} /* NB: In classical book typography, you would not also add margins between paragraphs;  text-indent is enough to signal a new paragraph. */

A large negative text-indent is often used to hide the text of an element while still applying other properties to it (which can’t be done using display:none;). This is the basis of the classic “image replacement” technique, where text content is hidden and replaced with a (background) image:

h1#logo {text-indent:-9999px; background: white url(logo.png) no-repeat 0 0; width:200px; height:100px; }

The Box Model

The box model can be confusing, but it comes down to two fundamental ideas. First, margin creates space between elements, while padding creates space inside elements. The difference is a lot more obvious when an element has a background, a border, or both.

You can specify the values on particular sides individually:

div#sidebar {margin-top:20px; margin-bottom: 10px; padding-top:20px; padding-bottom: 10px;}

Or use the margin and padding shorthands. Use an analog clock as a reminder of the order (top right bottom left)

div#sidebar {margin: 20px 10px 5px 7px;} /* margins-top: 20px, margin-right:10px, margin-bottom:5px, margin-left: 7px */

The other shorthands:

div#sidebar {margin:20px 10px;} /* margin-top AND margin-bottom are 20px, margin-left AND margin-right are 10px */
div#sidebar {margin:12px 7px 8px;} /* margin-top is 12px, margin-left AND margin-right are 7px, margin-bottom is 8px; */

So here’s how we would apply a gray background to blockquotes, inset the type inside that gray box by 5px, and then inset the whole thing by 20px on either side from its container’s edges:

blockquote {margin: 0 20px 0 20px; padding:5px; background-color:gray;}

The second big idea behind the box model: margin and padding both get added to any width and height settings you have specified, which is a little unintuitive.

div#sidebar {width:200px; padding:20px; margin:20px 10px; }/* takes up 260px of horizontal space */
nav  {height:50px; padding:10px 20px; margin-bottom:20px; }/* takes up 90px of vertical space */


Unordered lists (ul) and ordered lists (ol) both have list items (<li>) nested inside them. By default, browsers add bullets to unordered lists and sequential numbers to ordered lists.

Traditionally the ul has been used for all sorts of text content that needs to be grouped together but doesn’t involve running text (as in a paragraph). A set of navigation links are the most common example, and we can use CSS to style them any way we want. (NB: list-style is technically shorthand for list-style-type, list-style-position, and list-style-image, but it’s rare to need those three properties on their own).

nav ul {list-style:none; } /* remove bullets *
#main ul {list-style:disc; } /* change bullet style from solid circle to disc */


Borders are useful both to create visual boxes and also to create horizontal or vertical lines. Here’s we put borders on all four sides of the element:

div#sidebar {border-width: 2px; border-color:gray; border-style: solid;}

The shorthand below is useful, especially when applying a border to just one side (border-top, border-right, etc.). Remember to always use the sequence border-weight, border-style, border-color:

div.sidebar {border: 5px solid gray;} /* put a border around the whole sidebar */
div.sidebar a {border-bottom: 1px dotted blue;} /* underline links inside the sidebar */


When applying background colors, it’s simplest to use the background-color property on its own

div#sidebar {background-color:gray;}

But when applying a background image, I recommend the background shorthand. Include all these elements and don’t change the order: background-color, background-image, background-repeat, background-attachment, background-position. Note that transparent is a legitimate and useful value for background-color. background-position requires horizontal and vertical values (e.g. 2px 5px, left top, center center, 30% 50%, etc. And finally, background-attachment can be scroll (the default) or fixed.

section#main {background: transparent url(images/pattern.png) repeat-x left top;}

Cheat Sheet: Inline vs. Block Revew

Related to the box model is the distinction between block-level elements and inline elements.

Block-level elements (e.g. p, h1 through h6, ul, li) take up their own horizontal line and expand to fill the space available to them. For example, if you have a short heading (like <h3>My Skills</h3>) and apply a border-bottom to it, that border will extend well past the end of the word and won’t stop until it hits the edge of the containing element (your div or article or whatever).

Inline elements (e.g. a, img, span, strong, em, input) are part of the natural flow of running text and don’t take up their own lines by default (think of how you can wrap a phrase with the <strong> tag and it won’t push anything to the next line). These elements also don’t always respond to margin and padding as you might expect.

Now for the important part: you can change the behavior of any element using the display property.

Use display: block; to force an inline element to behave like a block-level element:

nav li a {display:block;} /* force the clickable link to expand to the full width of the list item */

Use display: inline; to force a block-level element to behave like an inline element:

nav ul li {display:inline;} /* force the li's to sit on the same line as each other */

There’s one more option: display:inline-block forces an element to acquire a sort of mixture of the two properties: the element will be inline in the sense that it will follow the flow of running text and sit side by side with adjacent content (also, borders will surround only the text itself, not the whole link). But it will be block in the way it reacts to width, height, margin, and padding:

nav li a {display:inline-block; border:1px solid blue; padding:3px; margin-right:20px;} /* put nav items in a row but allow block-like properties to be applied */

Keep in mind that display:inline-block has weak support in IE7 and lower.

Cheat Sheet: CSS Selectors

CSS selectors are the part of CSS syntax that “target” or “select” an HTML element or elements to be styled. In pseudo-code, a CSS statement look like this:

selector {
	property: value; /* declaration 1 */
	property: value; /* declaration 2 */

Use a tag name by itself to target a particular HTML element:

p {font-family:helvetica, arial; font-size:12px; line-height:18px;}
h2 {color:gray;}
div {padding:20px;}

Use a comma to target multiple HTML elements with a single expression:

ol, ul {list-style:none;}
p, h2, h3 {margin-bottom:10px;}

Target any HTML element of a particular class:

.warning {color:red;} /* matches <p class="warning">, <ul class="warning">, etc */
.intro {font-size:14px; line-height:18px;}
.caps {font-size:90%; letter-spacing:1px;}

Target any HTML element of a particular ID (should only match one element per page at most, since IDs must be unique to the page):

#sidebar {float:right; width: 30%;}

Target a particular HTML element of a particular class:

p.warning {color:red;}
div#sidebar {float:right; width: 30%;}

Target a particular HTML that has multiple classes:

p.warning.intro {font-weight:bold;} /* matches <p class="warning intro"> and <p class="warning intro awesome"> but NOT <p class="warning">*/

Use descendency to target elements that appear inside of others:

#main p {font-size:12px; line-height:16px;}
#main ul {list-style:circle;}
#sidebar ul {list-style:disc;}

Combine these techniques to get more granular control over your elements:

#main p.warning {color:red;}
#sidebar p.warning {background-color:red; padding:2px; color:white;}
#sidebar p.warning.intro {background-color: orange;}

Use a colon to indicate pseudo-classes. Here are the most common:

a:hover		{border-color:red;} /* invoked on mouse-over */
a:active	{border-color:orange;} /* invoked during mouse-down */
input:focus {background-color:yellow;} /* invoked while cursor is in the field */
li:first-child {margin-left:0;} /* targets the first list item in a set of list items */

Use the attribute selector to target elements of a particular attribute:

img[alt] {border-color:red; } /* matches all images that HAVE an alt attribute */
input[type="text"] {padding:2px;} /* matches all inputs whose type is "text" */