Search Results

Keyword: ‘tex+align’

Text Replacement Roundup: The Pros and Cons of SIFR, Cufon, Typeface.js, and FLIR

Those of you who have explored rich typography solutions for web development should be very familiar with the different techniques floating around the Internet. Until majority of the population uses browsers that support CSS3, and until commercial font licensing issues allow use of the @font-face rule to become a norm, many resort to these font embedding techniques.

The thing with non-standard font embedding techniques is that they mostly rely on JavaScript and sometimes Flash or PHP to render text in whatever custom font is specified. Thus, choosing the right solution for a web project can become tricky. This article aims to compare them by listing the pros and cons of each technique.

Scalable Inman Flash Replacement (sIFR) / sIFR 3

Probably one of the first full-blown text replacement solutions, SIFR uses a combination of JavaScript, CSS, and Flash to render custom fonts.

Pros:

  • Fully accessible to screen readers and assistive technology
  • Partially selectable text (cannot select surrounding elements)
  • jQuery integration
  • Anti-aliasing results in crisp font rendering
  • Flash-based font embedding is generally an allowable practice by most font foundries
  • Easy to add text effects such as shadows in Flash

Cons:

  • Requires Flash
  • CPU and memory intensive
  • Font license restrictions can be difficult to set up (e.g. Flash loading needs to be locked to your domain)
  • Can be tricky to set up
  • Embedded fonts cannot be printed

Cufon

Cufón aims to become a worthy alternative to sIFR, which despite its merits still remains painfully tricky to set up and use.
Pros:

  • Easy to set up
  • Does not require Flash
  • Fastest loading and processing time (according to this presentation)

Cons:

  • Inability to highlight and copy/paste text
  • License issues prevent many fonts from being legally embedded
  • Does not support justified text alignment
  • Hover state for elements other than links might result to unpredictable results
  • Requires extra JavaScript to prevent FOUC on IE7

Typeface.js

Typeface.js is similar to Cufon, using a JavaScript engine to render fonts on a browser using canvas or VML.

Pros:

  • Easy to set up
  • Does not require Flash
  • Fast loading and processing time

Cons:

  • Fonts are only selectable in browsers that support <canvas>
  • Hover state is not supported, but a workaround that requires extra code is available
  • License issues prevent many fonts from being legally embedded
  • Long loading times in IE
  • Only supports TTF (does not support .otf, PFB, and postscript fonts)
  • Requires extra JavaScript to prevent FOUC on IE7
  • Has spacing issues, according to some people

Facelift Image Replacement (FLIR)

Facelift Image Replacement (or FLIR, pronounced fleer) is an image replacement script that uses JavaScript, PHP and the GD library to dynamically generates image representations of text that use custom fonts.
Pros:

  • Does not require Flash or JavaScript
  • Fonts are rendered as an image and does not violate font licensing terms
  • Many text effects available thanks to Imagemagick

Cons:

  • Inability to highlight and copy/paste text
  • Can be painful to set up
  • Requires a web server with PHP and the GD library enabled
  • Finer details of fonts are not rendered very well by the GD library
  • Takes up additional server resources to process (bandwidth and CPU)

The good thing about these techniques is that they all take into account things like accessibility, SEO readiness, and browser support. These are all huge factors in web development today. For Internet Explorer users, IE6 is supported at least, and for non-supported browsers, thankfully every one of them degrades gracefully into your standard HTML rendered text.

In conclusion, every one of these techniques has its own set of advantages and disadvantages. sIFR is the oldest and most “proven method”, however it relies on both Flash and JavaScript thus taking a hit on performance. FLIR uses the old school technique of replacing text with images and even offers text effects. However, it is hardest to set up and requires a web server with PHP and the GD library enabled.

Typeface and Cufon are the most promising beign the easiest to setup. On the other hand they are both plagued with licensing issues and lack of ability to select text, which for many can be a deal breaker. This appears to be changing though, as Type Select builds on top of typface.js and promises text selection functionality. Still, it is a relatively new player and is also plagued by limitations such as lack of support in IE and no support for :hover and line breaks.

Share

Read More

CSS Blog

SlickMap CSS Lets You Create Beautiful Visual Site Maps Easily

Bored with the same old uninspiring, list-based sitemaps? If you’re like me, most likely you will find that creating better looking sitemaps can be quite time consuming. Thus, we end up having to settle for text-based unordered lists that look nothing like a map.

Well well well, worry not my friends, for now you can have a very beautiful and visual site map with nothing more than your standard unordered list and some CSS magic. Thanks to the efforts of Matt Everson of Astuteo, LLC, who released for public consumption what they call SlickMap CSS.

SlickMap CSS is “a simple stylesheet for displaying finished sitemaps directly from HTML unordered list navigation. It’s suitable for most web sites – accommodating up to three levels of page navigation and additional utility links – and can easily be customized to meet your own individual needs, branding, or style preferences.”

The first thing that really impressed me with SlickMap was the way data is visualized. The arrangment, grouping, and color coding of data makes it very easy to identify and find relevant data. The “Home link” is color blue and found at the top left most corner, immediately followed by the “Main links”, also colored blue. Level 2 and level 3 links can be found below them, each level having its own color, with a connector leading to each link. “Utility links” are grouped at the top right corner, separate from the main map.

What’s even more amazing about SlickMap is that everything is implemented in pure CSS. There is not a single line of JavaScript to be found anywhere. It’s also very easy to implement. Simply create an HTML file with an unordered set of links and import the slickmap.css file. Couple this up with an online site map tool like WriteMaps and you should be all set to rock and roll.

It supports most standards-compliant browsers, which means Safari, Firefox, and Opera. Sorry, IE but no love for you.

In the README file:

SlickMap CSS was created for web designers, and such was tested and developed for use with Safari, Firefox, Opera, and other standards-compliant browsers. Because of that, current versions of Internet Explorer (and probably IE versions long into the future) might look like sh*t.

The only downside I could think of right now is actually a strength in itself. While those large boxes would work for small to medium websites with a fairly standard site map layout like the one Astuteo has, it might do very well for larger websites with hundreds of links on their site maps. But then again there are methods to optimize and trim down those gigantic things.

It is a very well thought out and solid demonstration of the power of CSS, and for this reason I raise my glass and give my kudos to Matt Everson and the folks at Astuteo. Well done guys!

Share

Read More

CSS Blog

Flutter, the “ultimate wordpress CMS” updated

You use WordPress as a CMS right? And you probably love it, after all what is not to love? It is simple, easy to install, has a huge community base, thousands of plugins and themes… and 2.7′s interface is simply… stunning.

WordPress is not perfect as a CMS however, and can you blame it? It was designed to be a blogging platform. They must have done something right if WordPress started as a blogging platform that simply works so well as a CMS.

This could all be part of the past now that Flutter has arrived. WordPress could easily be a fully extendable CMS with one of the best blogging platforms integrated into it. So many of the minor pitfalls wordpress previously had as a CMS are now gone.

Flutter is not a new plug in by any means. Released around wordpress 2.5, it has had time to pick up a little bit of steam. It seams it never really caught on because despite it’s useful benefits it was confusing and difficult to install and maintain. To wordpresses recent credit, it didn’t solve some of the more confusing “blog focused interface” that 2.5 and 2.6 still had.

However now coupled with 2.7 and a new release of flutter you can now create an amazing full fledged CMS capable of almost anything you can think of.

More About Flutter

Flutter was designed to combat two major issues that WordPress has when being used to administer and power web sites rather than blogs. Dealing with content that was more than just self formated text and photos, and an easy way to edit complex pages.

Custom Content Types

A typical example could be pages for the biographies of individuals. These pages likely have a specific format that all of them should adhere to. Name, Title, Skills, etc… Previously with WordPress you would create a blank page for each and have to try your best not to accidentally mess up the format. Of course you could try using the custom fields, but try explaining those to a client with out having their eyes glass over.

Now days you had better count on the fact that websites are going to be complicated enough where the simple homepage / innerpage templates are not going to be substantial. Websites will have different content types, a home listing, biography, portfolio page, etc… Flutter allows you to create custom write panels for different types of content. The write panels can have text fields, radio buttons, pictures, drop downs, etc… allowing the user to create a page exactly how they want it with out hassel or vast technical knowledge.

Edit in Place

The other example might be managing and editing pages that have both unique sidebar content and primary content. Before you would have to create a page for the sidebar, use a custom template to include that post into the sidebar before finally trying to teach a client how it all works. Very complicated right? Well it doesn’t have to be.

Flutter also lets you specifcy editable regions of a page, like the main content, title, or sidebar. Using a bit of AJAX magic useres who are logged in can navigate to the page they wish to edit through the front end, click an edit button, and begin to edit that section with out even leaving the page.

This makes the CMS almost transparent. Your typical client is more familiar with the web from a users perspective, and this allows them to edit and manage pages the way they are most comfortable.

Slightly Complicated

While the usage and learning curve of flutter has improved, you should still expect to spend an ample amount of time your first attempt at using this plugin. The documentation while available, is sparce at best (not that you can really blame the developers, who are giving the plugin for free.)

The learning curve is well worth it. You can easily expect to save more time than you spend in reduced phone calls and e-mails regarding how to perform specific functions, tasks, or edits in WordPress.

Read More

CSS Blog

Those familiar with fluid / elastic layouts know that they can be a little more challenging to implement compared to fixed-width layouts. With the advent of wide-screen monitors, one of the biggest advantages of fluid-width layouts is the ability to maximize available space.

It was only a year ago when 1024×768 was still the dominant screen size. However, as of January 2009, 57% of the population are on desktops higher than 1024×768. The number of users still on 1024×768 has declined sharply from 48% of the previous year to a mere 36%. On the other than, the users on widescreen desktop are rapidly growing, thanks in part to marketing by HDTV makers.

Kayla Knight has written a very good article on the topic of building good websites with fluid layout.

She comes up with 6 techniques to do this, which can be summed up as follows:

  1. Fluid Layout Using A Grid
  2. Adaptive Content
  3. Images In A Fluid Layout
  4. jQuery Masonry
  5. Smart Columns with jQuery & CSS
  6. Text Zooming

She also provides helpful examples and links to all the necessary tools needed to achieve the perfect fluid / elastic layout. With this, designers are armed and ready for the next evolution in layout design.

Read the full article

Share

Read More

CSS Blog

Featured CSS Library: Better Web Readability Project

The Better Web Readability Project aims to promote screen-friendly and more readable fonts. The result is a CSS library that redefines, among others, the standard font size as well as leading (the amount of space between text). Other features of this library are:

  • 16px default main text size
  • Partial 26px baseline grid
  • Serif for Heading, sans-serif for the paragraphs
  • Lower color text contrast
  • Intensified paragraph division (new line + indent)
  • Bigger leading (line-height) 1.625

The original idea came from Vladimir Carrer, who also came up with the library. In his post entitled How we read on web and how can we improve that he reveals that most of us who use computers to read news, blogs, and various sites end up scanning rather than reading. He then compares reading a book to reading on the monitor, and provides three reasons why it is harder to read on a computer screen:

  1. We maintain the book standards (12pt) for font size on the web (12px). But the distance from the monitor is triple. Just put your newspaper to your monitor and try to read. Hell! Is hard!
  2. Additionally the paper reflects the light and monitor emits the light. If you have old “cathode” monitor it’s like looking directly in a light bulb.
  3. You also have distraction noise: strong colors, links, flash animation, banners , not defined site architecture, click here, digg me, follow me on twitter, by my products… it’s fucking jungle out there.

He then comes up with a set of standards and rules that would allow for better and easier on-screen reading, and packages it as a CSS library. The resulting text is beautiful and pleasing to the eyes. One such example can be seen in the screen shot below. You should notice how your eyes would easily glide through the text:

Better Web Readability Project example screenshot

You can head over to the project homepage, or click on the links below to view the library in action:

You can also head over and download the full library here.

Share

Read More

CSS Blog

Survey For People Who Make Websites 2008 Results Out

Back in 2007, the staff of A List Apart and An Event Apart conducted a survey and presented 37 questions to 33,000 web professionals, providing “the first data ever collected on the business of web design and development as practiced in the U.S. and worldwide” (ALA 2007 results). The results were compiled into a downloadable PDF file.

In 2008 they did it again, the results of the 2008 Survey For People Who Make Websites are now out for public consumption. The survey had less respondents compared to the one held in 2007 down to 30,055. Data analysis is provided by Alan Brickman and Larry Yu. The results speak can be overwhelming for some. Thankfully the findings are presented in a friendly, easy to read article with clear and beautiful CSS Charts.

ALA has generously shared the raw data with the community, which is available as tabbed text, CSV, and Excel spreadsheet. RAW data is a powerful thing, and I just have a couple of suggestions how it can be used:

  • AJAX application that allows visitors to enter their own responses, and generates a graph that shows where the respondent is in relation to others
  • Quick summary that shows the highest and lowest result per question
  • AJAX application that allows visitors to filter, sort, and sift through the data
  • Side-by-side comparison of 2008 and 2007 data

All in all, big props to the ALA team for the tremendous effort spent on this endeavor. It is a great contribution to the web community. Looking forward to the 2009 survey!

Share

Read More

CSS Blog

A Simple jQuery Stylesheet Switcher

jQuery stylesheeet switcher

There are lots of reasons you might want to offer your users more than one CSS file for your website:

  • You want to offer a “stylish” low-contrast and an easy-to-read high-contrast version of your site.
  • You have many low-vision readers and want to give them easy access to a customized stylesheet with a larger typeface.
  • Your site is schizophrenic and you want to be able to change the look quickly.

Whatever the reason, it’s amazingly easy to create a function that swaps between multiple stylesheets using jQuery.

The first step of course is to build several different CSS files, which we’ll then swap between. Once that is done, we can dive into the XHTML and jQuery that makes the magic happen.

The XHTML

First, we need to create a set of links that will allow the user to swap between CSS files. You can make this as simple or as fancy as you’d like. For the sake of brevity, my links are simple:

<ul id="nav">
	<li><a href="#" rel="/path/to/style1.css">Default CSS</a></li>
	<li><a href="#" rel="/path/to/style2.css">Larger Text</a></li>
	<li><a href="#" rel="/path/to/style3.css">Something Different</a></li>
</ul>

Here I have three links, each with a “rel” attribute indicating which CSS file the link will load. Technically, I could have just as easily put this information in the “href” attribute, but I didn’t want to for one specific reason: if the user has JavaScript disabled and the CSS file is listed in the href, then clicking the link will send the user to the CSS file directly (not loading it like we intended). But our way, if JS is disabled, the user gets nothing at all: which is certainly preferable to the less savory alternative.

The jQuery

Like I promised, the jQuery is really simple:

$(document).ready(function() {
	$("#nav li a").click(function() {
		$("link").attr("href",$(this).attr('rel'));
		return false;
	});
});

This function waits until the document is loaded (generally an important step when interacting with the DOM), then attaches a click function to each of our nav anchors. The function basically says, “when someone clicks on this link, replace the link (stylesheet) tag’s href attribute with the contents of this link’s rel attribute.” The “return false” at the end just stops the browser from trying to follow the link.

Of course, you might have to get more detailed if you have more than one link tag, for example, but that’s easily done by giving the link tag a class (”changeme,” for argument’s sake), and writing something like this:

$("link.changeme").attr("href",$(this).attr('rel'));

And while this stylesheet switcher is already complete, we might want to give it some memory: after all, your users might get annoyed if they have to switch their styles back to their preferences every time they visit your site. For that, we’ll need to set a cookie. And to make that easier, I’ll use the jQuery cookie plugin (which I’ve talked about previously when building a popout ad).

With the plugin loaded, we can modify our jQuery thusly:

$(document).ready(function() {
	if($.cookie("css")) {
		$("link").attr("href",$.cookie("css"));
	}
	$("#nav li a").click(function() {
		$("link").attr("href",$(this).attr('rel'));
		$.cookie("css",$(this).attr('rel'), {expires: 365, path: '/'});
		return false;
	});
});

Now we have two statements. The first one checks as soon as the page is done loading to see if a cookie called “css” has been set. If so, it sets the stylesheet to be the one indicated in that cookie. Otherwise, it does nothing.

Our click function is much the same, except after we set the stylesheet, we also set a cookie. This cookie doesn’t expire for an entire year (and each time the user changes their stylesheet preferences, it would reset this timer), giving them a good 365 of CSS bliss.

Fine Tuning

There is one minor annoyance with this stylesheet switcher: there’s generally a flash of the “default” CSS when the user loads the page. That’s because the script waits until the document is “ready” before switching the link’s href. There is a way around this: moving the first “if” statement outside of the document ready function, like so:

if($.cookie("css")) {
	$("link").attr("href",$.cookie("css"));
}
$(document).ready(function() {
	$("#nav li a").click(function() {
		$("link").attr("href",$(this).attr('rel'));
		$.cookie("css",$(this).attr('rel'), {expires: 365, path: '/'});
		return false;
	});
});

Generally speaking, you don’t want to run any jQuery until your document is ready. However, so long as your jQuery comes after your link tag in your document structure, like shown below, this shouldn’t be a major concern:

<link rel="stylesheet" type="text/css" href="style1.css" />
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript" language="javascript" src="jquery.cookie.js"></script>
<script>... your jQuery goes here...</script>

This means your jQuery will run before the document is done loading, and thus your link tag’s href will be swapped before your CSS has been applied. As I said before, it’s generally a bad idea to manipulate the DOM before document ready, but because we know the exact tag we want to manipulate and can place our jQuery below it in the DOM, we should be safe in this one specific instance.

Here’s an example if you would like to see this technique in action.

Read More

CSS Blog

15 Surefire Ways to Break Your CSS

'Fixed' by Don Fulano. Used under a Creative Commons license.

The life of a CSS developer isn’t all about attending glamorous champagne parties, jet-setting around the world and hanging out with supermodels. In fact, when your CSS doesn’t behave the way it should, the job can be downright tedious. I’ve spent untold hours of my life debugging my code — and I’m guessing I’m not alone here.

But as silly as it may seem, some of the biggest CSS blunders stem from the simplest of errors. Knowing what some of those errors are and remembering to look for them can save you hours of wasted labor. Here are fifteen ways I’ve found to break my CSS for sure — and fifteen things I always look for whenever I have a problem in my code.

Missing a Semicolon

CSS rules are comprised of property-value pairs (declarations) followed by a semicolon. Accordng to the CSS specification, the last declaration doesn’t need a semicolon — because the closing brace effectively ends the declaration just as well. That means something like this is perfectly acceptable:

body {
	background-color: #444;
	color: #eee }

The only problem is, as soon as you decide to add another declaration to your previous rule, you’ve now made it all too easy to forget to add the semicolon to your once-last rule:

body {
	background-color: #444;
	color: #eee
font-family: Helvetica, Arial, sans-serif }

The result? Your font-family rule never gets applied, because the parser reads “font-family” as part of the color value. Which is why I make a habit of adding the final semicolon in a rule, no matter what.

Missing a Colon

I’ve seen this particular problem crop up frequently while teaching classes on CSS. People get excited when CSS starts to make sense, and their typing speed increases. The downside: this makes errors of omission much more likely. And a missing colon is particularly tough to see, since it sits right in the middle of a declaration. Consider the following two lines:

body { font-family Helvetica, Arial, sans-serif; }
body { font-family: Helvetica, Arial, sans-serif; }

It’s easy to see how the colon could get overlooked in the jumble of braces, hyphens, semicolons and cryptic words. As a rule of thumb, if you only have one declaration not behaving itself, this is a good place to start looking.

Missing a Brace

{Braces} around a CSS rule are like the circle of life: regular, natural, and expected. And if you ever miss a brace (generally a closing brace for whatever reason) — just like if you have a zombified corpse that refuses to die — you suddenly have all sorts of mayhem on your hands.

When an unsuspecting browser comes across a pair of rules like this:

body {
	font-family: Helvetica, Arial, sans-serif;
#wrap {
	width: 960px; }

The browser is going to choke. Two opening braces before a closing brace is right out: everything from your #wrap rule (in this example) on would be ignored.

However, this does make debugging easier. Do you have a whole chunk of CSS being ignored? Which is the first rule that is being neglected? There’s a good chance you have an uneven number of braces hanging out in the vicinity.

Misspelled Properties

I consider the following few errors the bane of dyslexic developers everywhere. Generally speaking, I’m a good speller. But when I’m “in the zone” and typing as fast as my fingers can carry me, I tend to transpose a few letters here and there. In writing, this isn’t such a big deal: people can generally figure out what I mean. Computers, sadly, are less discerning.

div { border-bototm: 5px; }

Now, I have no idea what a “bototm” is, but I do know I write the word at least one time in five when I’m trying to refer to the lower edge of an element. I’m lucky in that I have a decent eye for editing and often catch these mistakes as I make them. If you’re not so fortunate, using a program with code coloring like Notepad++ or Adobe Dreamweaver (my personal favorite) can make the job a lot easier: if a property isn’t colored like the other properties, than it’s probably not much of a property at all.

Misspelled Values

Misspellings aren’t limited to just properties. And sometimes a misspelled value can be even more difficult to notice:

#wrap { padding: 10px 20pz 25px 20px; }

Unfortunately for the rule above, I’m fairly sure only Snoop Dogg and I have ever tried to measure elements in pizzles. Instead of the generous padding you’d expect this rule to generate, this one misspelled unit renders the entire declaration invalid.

Misspelled Classes and IDs

No matter how often I create a div with an ID of “navigation,” I still find myself writing rules that look more like this:

#navigaiton { float: left; } 

This can be a frustrating error to track down, because color-coded editors won’t help you out here: you could just as easily purposefully name an element “navigaiton” if you really wanted. But I’d recommend against it.

Improperly Ordered Values

Some CSS properties have a built-in shorthand, which is a great way to save yourself a few lines of code. Unfortunately, most of the shorthand properties are very picky about the order of the property’s values. For example:

div { font: 2em Helvetica, Arial, sans-serif; }
a { font: "Times New Roman", serif 1.5em; }

The first rule will result in all divs gaining a specific typeface and size. The second rule will result in a debugging session — while it’s okay to leave some values out of the font declaration, changing up the order of the values will result in problems.

Measurement Values Without Units

CSS Newbie reader Justin reminded me of this problem the last time I wrote about CSS faux pas. With only a few limited exceptions, all measurement values in CSS need a unit of measurement associated with it. Take the following rule for example:

#wrap { margin: 3; }

Three what? Ems? Inches? Pizzles? The flexibility of CSS that allows us to pick from several units of measurement also means specifying a unit is fairly important.

Bonus — Two unit-agnostic measurements:

  1. Values of zero don’t need a unit of measurement. Turns out, zero pixels and zero miles are exactly the same length.
  2. Line heights needn’t have a specific unit. A line height of “1.5″, for example, will simply assume you meant “1.5 times my font size.” For more on this phenomenon, visit Eric Meyer’s article on Unitless Line Heights.

Competing Identical Rules

Once a stylesheet gets to be a certain length, it can be difficult to remember which rules you’ve already written unless your CSS is very well organized. And two identical rules at different spots in your CSS file can wreak havoc on your design and sanity alike.

ul li { margin: 0 2em; }
... 300 lines later ...
ul li { margin: 0; padding: 10px; }

In this scenario, the latter rule would win out over the former, thus removing the margin and applying padding instead. But if you’ve forgotten about this duplicity, you might go back into your CSS later and try editing the first rule only, and remain perplexed as to why, no matter how you tweak your margin, you can’t seem to make any difference.

Unintentionally Competing Rules

A similar problem could force your CSS to compete with itself in ways you didn’t expect. For example, if you had the following code in your XHTML:

<div id="navigation" class="nav">...</div>

You could refer to this element by either its class or its ID. The problem arises when you do both, and forget that you’ve done so:

.nav { width: 50%; }
... later in the code ...
#navigation { width: 500px; }

This code would result in a fixed-width navigation bar, even though the first rule would suggest a more flexible width. Again, having a well organized stylesheet is the easiest way to avoid this problem.

Calling a Class an ID (or vice-versa)

I fall into this particular trap all the time. I’ll write a rule like this:

.navigation {
	float: left;
	width: 100%;
	height: 4em; }

And nothing will happen! It often takes me a minute or two to realize that the real problem is that I’d given my navigation bar an ID, not a class. My best advice here is to pick a naming system that works well for you and be consistent. If you always call your top navigation bar “#topnav”, for example, you’re far less likely to misremember your element names.

Using a Nonexistent Property

Not all CSS properties are named the most intuitively. For example, this might look like a perfectly acceptable rule to someone new to CSS:

body { text-size: 3em; }

The problem is, while there are certainly several text-riffic properties, text-size isn’t one of them. Instead, we use font-size. Which means that the rule above wouldn’t do much of anything. Intelligent code-coloring editors like Dreamweaver usually make this sort of debugging much easier: if it’s not a real CSS property, it won’t be the same color as the surrounding properties. That’s usually my first clue I’ve done something wrong.

Using a Nonexistent Value

This is a sister stumbling block to the one above. Some values just seem to make sense, but will fail you nonetheless:

td { vertical-align: center; }

You would assume that this rule would vertically center your table text, right? Unfortunately, while “center” is indeed an acceptable value for text-align, vertical-align uses the perhaps less intuitive “middle” instead. And you’d have to ask a better educated rhetorician than me to figure out the difference between middle and center in this context, because I’m at a loss.

Improperly Matching Properties and Values

Certain CSS declarations can look correct even to the trained eye, unless that eye is paying particularly close attention. For example:

a { text-transform: italic; }

While this might look like a perfectly reasonable rule, you won’t end up with italicized text. That’s because “italic” belongs to the font-style property, not the text-transform property. But even most advanced editors won’t catch that bug, as you’ve used a perfectly reasonable property and value — you’ve just used them in an inappropriate combination.

Not Closing Comments

The gentle persons at BlogThemeMachine tipped me off to this common CSS problem. Can you spot the major difference between these two sets of rules?

/* Navigation goes here. */
#nav {
	float: left;
	width: 100%;
	height: 3em; }
/* Navigation goes here. /*
#nav {
	float: left;
	width: 100%;
	height: 3em; }

The only difference is that the second rule has an improperly closed comment tag: /* versus */. That seemingly insignificant difference can result in entire swaths of your CSS suddenly not working. In fact, this tiny blunder will negate all your CSS from the start of your comment until you successfully close a second comment. Which if you’re using comments to organize your CSS means an entire section of your site will lose its styling.

These fifteen tiny blunders are sure to give you hours upon hours of CSS frustration… unless you know to watch for them. What are some other self-introduced bugs you often find in your code? I’d love to hear about them in the comments!

Read More

CSS Blog

Build a Tabbed Box with CSS and jQuery

tabbed box

The longer a site has been around, the more content it tends to accumulate. As website operators, we walk a fine line: too much content on every page and your site will look cluttered. Too little, and users won’t be able to find all your website has to offer. A tabbed box like the one pictured above is a nice bridge between the two extremes. It allows you to show off a large amount of content without cluttering up a lot of space. And this tabbed box has extra niceties that are sure to help your content get noticed.

What it Does

At the end of this two-article series, you’ll be able to build a tabbed content box of your own that:

  • Is easily customized to fit the size and color scheme of your website.
  • Is either fixed or variable height.
  • Can automatically rotate through the tabs to draw interest.
  • Pauses its rotation when the user interacts with it.

This article will show you how to take the tabbed box from Photoshop to XHTML and CSS, and how to apply the basic jQuery functionality to make the tabs operate. The next article will show you some advanced jQuery techniques to make your tabbed box even more dynamic and eye-catching.

The Photoshop Mockup

Like most of my projects, this one started life as a drawing roughly sketched out on a piece of paper. Despite all the cool tools we web developers have at our disposal, paper and pencil are still by far the fastest way to rapidly prototype a new idea. Here’s a crappy iPhone photo of the drawing:

drawing of a tabbed box

This is what I mean when I say I’m not a designer, people.

Once you have a good idea as to what you’re looking to do with your tabbed box, it’s time to move into Photoshop (or a similar editing tool). If you’re looking for an extremely barebones tabbed interface you can probably skip this step entirely, but I wanted my tabs to have a little pizzazz. Here’s a look at my Photoshop document:

tabbed box in photoshop

It’s nothing fancy: just two layers with gradients, a layer creating my borders, and my text. Of course, your layout may be more complex than mine.

When I’m working in Photoshop, I like to stop and think about how I’m going to actually develop what I’m building (and I’d advocate you do the same!). In this case, I knew that I wanted gradients on both my unselected tabs as well as the content box and that my unselected tabs should appear faded. Once I had a pretty good mockup in place, I could start to visualize how my XHTML and CSS would work together to produce the result I was looking for.

tabbed box's outline of parts

The XHTML

Here’s the basic XHTML I decided on for my tabbed box:

<div class="tabbed-box">
	<ul class="tabs">
		<li><a href="#">Tab #1</a></li>
		<li><a href="#">Tab #2</a></li>
		<li><a href="#">Tab #3</a></li>
	</ul>
	<div class="tabbed-content">
		<p>Here's my content for tab 1</p>
	</div>
	<div class="tabbed-content">
		<p>Here's my content for tab 2</p>
	</div>
	<div class="tabbed-content">
		<p>Here's my content for tab 3</p>
	</div>
</div>

I wanted to keep my XHTML as simple as possible, so that if I ever wanted to update the content my tabbed box, I wouldn’t have to dig through a lot of extra code to do so. The box has three basic components: a wrapper div (tabbed-box) that holds my entire box together, an unordered list with links that will function as my tabs, and a series of divs (tabbed-content) to function as the containers for my tabbed content.

I decided early on to stay away from extra IDs on all my elements as much as possible, to keep the updating process as simple as possible. Of course, that meant my jQuery would have to work smarter to figure out how the box works… but we’ll get to that later.

The CSS

Developing the CSS for this box does take a little math and a good understanding of the box model, but it’s not overly complex. First we’ll style our container box:

.tabbed-box {
	width: 302px;
	background: #fff url(tabbed-body-bg.jpg) repeat-x bottom;
	border: 1px solid #ddd; }

The width here is the most difficult number to determine. To come up with the number, I need to know two things: how much space I have to work with, and the number of tabs I plan to have. (I could probably calculate all this dynamically in jQuery, but I prefer to use CSS to accomplish as much as possible before turning to scripting.)

The space allotted is determined by the size of the tabbed box’s containing element: I built this box with CSS Newbie’s sidebar in mind, which gave me just over 300px of breathing room. Next up, I need to consider the number of tabs I’ll have. My box will have three tabs. If each of those tabs are 100px wide, they then use 3 * 100 (300) pixels of space. But don’t forget: according to our design, two of those tabs will need a border on one side to create the tabbed effect. This results in another two pixels added to our width, for a total of 100 * 3 + 2 (302) pixels. But remember, with the borders I added to my tabbed-box class, my final overall width is 100 * 3 + 2 + 2 (304) pixels.

Next up, we’ll style our tabs:

.tabbed-box .tabs li {
	list-style: none;
	float: left; }
.tabbed-box .tabs li a {
	display: block;
	width: 100px;
	padding: 5px 0;
	font-weight: bold;
	text-align: center;
	text-decoration: none;
	color: #888;
	background: #fff url(tabbed-tab-bg.jpg) repeat-x bottom;
	border-left: 1px solid #ddd;
	border-bottom: 1px solid #ddd;}
.tabbed-box .tabs li:first-child a {
	border-left: none; }

First I’m removing the list style and floating my tabs to the left to get them lined up horizontally. Next I’m making them block-level, so the entire tab becomes clickable. Then I’m setting them to the appropriate width (100px in this case), giving them some padding, styling the text, applying my gradient background, and applying my borders to the left and bottom sides.

Next I have a rather specific rule: I’m removing the left border on the first-child element: this means that my very first tab won’t have a border on its left side, since the containing box has a border there and we don’t want to double up. Of course, first-child isn’t supported by Internet Explorer 6… but don’t worry, we’ll account for that in our jQuery.

Then all we have left to get our tabs in working order is to set how they behave in three states: hover, focus, and “active”:

.tabbed-box .tabs li a:hover {
	color: #333; }
.tabbed-box .tabs li a:focus {
	outline: none; }
.tabbed-box .tabs li a.active {
	background: #fff;
	color: #333;
	border-bottom: 1px solid #fff; }

I’m giving my tabs a slightly darker text color in the hover state, to help the user see when they’re hovering. The focus state is there simply to remove the resulting outline in Firefox when the user clicks a tab: if you’re one of those who insist on having a focus state, feel free to leave this rule out. And finally, we have an active class. This class will be applied by our jQuery to the tab that is currently open. Here we’re removing the bottom border and changing the background color to give it the appearance of an open tab.

And last but not least, we need to apply some styles to our tabbed-content divs:

.tabbed-content {
	padding: 3em 1em 1em 1em;
	display: none; }

The padding simply pushes the content away from the edges of our box. You can set this to whatever you wish. And our display rule hides all our content, until it’s called upon by our jQuery.

The jQuery

Since we’re using the jQuery library to do most of our heavy lifting here, you’ll need to include the jQuery library somewhere above the following code.

Because I decided to write my XHTML without a lot of extra IDs and classes, my jQuery is going to have to be a lot smarter when it comes to figuring out which tabs display which content. My rationale is pretty straightforward: the first anchor in my unordered list should open the first tabbed-content div, the second one the second, and so on down the line. Because our logic is so straightfoward, I can rely on the jQuery index functionality to do a lot of the hard math.

var currentTab = 0; 

function openTab(clickedTab) {
	var thisTab = $(".tabbed-box .tabs a").index(clickedTab);
	$(".tabbed-box .tabs li a").removeClass("active");
	$(".tabbed-box .tabs li a:eq("+thisTab+")").addClass("active");
	$(".tabbed-box .tabbed-content").hide();
	$(".tabbed-box .tabbed-content:eq("+thisTab+")").show();
	currentTab = thisTab;
}

I start out by declaring a global variable that I’ll use throughout the script: currentTab. The currentTab variable will hold the index (an internal counter, like in an array) of the tab we’re currently on. It will also serve later to decide which tab we open by default.

Our function looks more complicated than it is. It requires one variable to be passed it: the clickedTab variable, otherwise known as the tab the user just clicked on. It then calculates the index of that tab (if it was the 3rd tab, the index would be 2) and saves that number as thisTab.

Next, the script cycles through all our tabs and removes any instances of the “active” class if finds, before cycling through a second time and applying the active class to the tab that has the same index number as the tab that was clicked on (in other words, the same tab). This ensures we only ever have one active tab at a time. Then we cycle through our content boxes, hiding them all before cycling through again and showing only the one box that has the same index as our tab… meaning if the third tab was clicked, the third box will open. That bit of math is what saves us from having to apply IDs to all of our tabs and content boxes. Then we set the currentTab variable to our newly open tab’s index.

Now that our function is written, we can get our tabbed box ready for prime time:

$(document).ready(function() {
	$(".tabs li:eq(0) a").css("border-left", "none");

	$(".tabbed-box .tabs li a").click(function() {
		openTab($(this)); return false;
	});

	$(".tabbed-box .tabs li a:eq("+currentTab+")").click()
});

The first line in our document ready function removes the left border of the first tab. Our CSS handled this for all browsers but IE6, but this bit of code takes care of IE6 as well.

Next, I’ve written a click function that will fire any time anyone clicks on any of our tabs. It only has two parts. First, it fires the openTab function, sending it a variable called “$(this)”. In jQuery, the $(this) variable in a function is always populated with the element on which the function was applied. So if the user clicks on the 2nd tab, our $(this) variable would contain that element. The “return false” after our function prevents the browser from trying to go to whatever we put in our anchor’s href.

And last but certainly not least, our final line forces a click on the tab with an ID that matches currentTab. In my example, that’s the first tab, but you can set currentTab to whatever you’d like to start, so long as currentTab is at least one less than the total number of tabs (since we start counting at zero).

And with that, we have a functioning tabbed box!

You can see this box in action here. The demo contains all the XHTML, CSS and jQuery you need to get this box up and running on your own site.

My next article will cover some advanced tricks you can do with this box, like getting it to cycle through automatically to catch the user’s eye… and how to stop the box from cycling once it has the user’s attention. To be sure to catch the article, you may want to subscribe to my newsfeed.

Read More

CSS Blog

12 Creative and Cool Uses for the CSS Border Property

random art using the CSS border property

If CSS properties attended high school, you would never expect to see the border property sitting at the cool kids’ table. Sure, it’s a useful property and all — as long as you’re looking accentuate the boxiness of a design, right?

Actually, you’d be surprised at just how cool the border property can be. Please take the following dozen exhibits as proof that the CSS border property is a lot cooler than we give it credit for.

Jazzing Up Anchors

I’ve written here before about jazzing up anchor tags by changing the color, removing the underline, and adding background images. But border can be a great way to add a bit of visual style to your anchors without adding that great bit of accessibility that the underline provides. For example, CSS Newbie’s article links are currently styled with a dotted border, like so:

.entry a {
	color: #253c93;
	text-decoration: none;
	border-bottom: 1px dotted #253c93; }
.entry a:hover {
	border-bottom: 1px solid #253c93; }

That gives me a nice dotted border that turns solid when the user hovers over the link. All sorts of style and accessibility without that so-’90s underline.

Build a Postage Stamp

CSS postage stamp

A while back, I ran across a cool little technique for faking a postage stamp using the CSS border property. The original link seems to have been lost from the web, but here’s the basic technique, in XHTML:

<div class="stamp">
	<p>99&cent;</p>
</div>

And CSS:

.stamp {
	width: 500px;
	height: 414px;
	background: #fff url(george.jpg) no-repeat;
	border: 12px dashed #1b1a19; }
.stamp p {
	color: #fff;
	margin: 10px 10px 0 0;
	font: bold 60px Georgia, "Times New Roman", Times, serif;
	text-align: right; }

Now, you could obviously take this even further with a bit of skill and a degree in something other than Rhetoric, but I think you get the idea. You can see the example live here.

Prettier Images

Borders are a great way to make your excellent images stand out even more. I wrote an article on the subject a while back, but here’s the basic idea:

img.photo {
	border: 1px solid #999;
	background-color: #fcfcfc;
	padding: 4px;}

You can see a similar technique used on CSS Newbie’s current design around all of the images in the articles, as well as the ads in the sidebar. As you can see, the technique can be subtle but visually pleasing if used properly.

Homemade Coupons

If you’re ever required to design an online coupon, you needn’t turn straight to Photoshop or the like. You can craft a coupon easily with just a bit of CSS:

.coupon {
	width: 250px;
	padding: 10px;
	text-align: center;
	border: 3px dashed #ccc; }

Just that speck of code gives me a nice coupon that looks something like this:

CSS coupon

You’ll have your readers printing and clipping in no time.

Better Blockquotes

CSS blockquote

Blockquotes are often useful, seldom used. But if you have a website that often refers to the words of others, a well-styled blockquote will go a long way towards impressing your readers with your borrowed prose:

blockquote {
	margin: 1em 3em;
	color: #999;
	border-left: 2px solid #999;
	padding-left: 1em; }

Just a touch of code, and voila… instant credibility!

Hunt Archaic Code

diagnostic CSS

If you ever take over a website (or perhaps built a website) that is still using the Code of Yesteryear, consider turning to CSS and the border property for help hunting down bits of HTML soup that could use a bit less seasoning:

font, center, s, u, b, i {
	color: #000;
	font-weight: bold;
	background-color: #f99;
	border: 3px solid #c00; }

For more information on this useful technique, see my article on finding deprecated elements with diagnostic CSS highlighting. It just might save your life someday. But I doubt it.

Round the Bend

CSS rounded  border

So far, all of our techniques have had one thing in common: boxy edges. But if you’re using a browser developed within the last five or so years (read: not IE6), you’re not limited to those same old dull right angles. This article from last August shows us that CSS3 offers us a way of breaking out of — or at least bending the corners of — the CSS box:

div.rounded {
	background-color: #666;
	color: #fff;
	font-weight: bold;
	padding: 10px;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px; }

The border-radius properties allow us to round the corners of elements without having to resort to images. Cool indeed!

Angle it In

Eric Meyer slant

Of course, not all angles are bad angles… if used properly. Way back in the day, CSS guru Eric Meyer pointed out a way to use borders to create some pretty wicked angles. If you’d like to learn more about this technique, his site is a great place to start.

CSS Drawings

And now for a bit of fun! The following excellent (and cool) examples are all drawn using the CSS border property.

CSS lcd clock

This functional LCD-style digital clock was built using CSS borders to create the lines of the LCD. Check out tanfa.co.uk to see it in action!

CSS skyline

There’s something very pop-art about this CSS skyline. It leans heavily on the border property to create the buildings and windows.

random art using the CSS border property

Here’s a random art generator that combines HTML, JavaScript, and the CSS border property to create random examples of modern art. If you hit the “update” button long enough, you’re bound to find something worthy of hanging on your (cubicle?) wall.

CSS house

Christopher Hester is a man with fantastic CSS skill, incalculable patience, and presumably no girlfriend — at least until he started impressing the ladies with this house he built with the CSS border property. And be sure to check out his second CSS house, which he built using background colors and approximately 50 gazillion non-semantic divs.

If you know of any other fantastic uses for the CSS border property, be sure to mention them in the comments!

Read More

CSS Blog