Renaissance Nerd

  • Random
  • Archive
  • RSS
  • Ask me anything

A Thought Experiment: Pixel Art

We know we can draw a 45-pixel × 45-pixel square using an empty div and some CSS.

.square {
    background-color: #fff;
    border: 1px solid #ccc;
    height: 45px;
    width: 45px;
}

And we know that we can make the square’s background color red using jQuery.

$('.square').css('background-color', 'red');

If we take this snippet a bit further, we can alter the square’s background color when it’s clicked.

$('.square').click(function() {
  $(this).css('background-color', 'red');
});

But what if we want to turn it off again—that is, what if we want the background of the square to be white if it’s clicked while the background is red?

$('.square').click(function() {
  var newBackground = ($(this).css('background-color') == 'rgb(255,255,255)') ? 'white' : 'red';
  $(this).css('background-color', newBackground);
});

Now we can toggle the square’s color like a switch. Which is utterly useless. Unless you float the square, duplicate it 15 times, wrap all 16 in a row, then duplicate the row 11 times. Now we have a 16 × 12 grid of squares that can be toggled on an off. We’ve created a pixel art canvas.

In this demo, I’ve taken the idea beyond just the basic grid of squares that can be toggled and added a rudimentary color palette. Each palette box uses an HTML5 data attribute—in this case, data-color—to hold the color of the box, which is set via JavaScript. Finally, using a conditional to check for the presence of on-touch handlers, I optimized the whole thing for use on the iPad, which was the ultimate goal of this experiment.

if ('ontouchstart' in document.documentElement) {
  // Handle touch events
  ...
}

When I started out, I didn’t know that onClick events suffer from a delay of a couple hundred milliseconds on touchscreen devices, which causes interactions to feel very sluggish if you rely on jQuery’s click listeners. You can see here how I wired up touch events in favor of click events when the page is loaded on a touch-enabled device. The JavaScript isn’t pretty, but it’ll suffice for a project that I spent about an hour on.

There was no real purpose to this, no ultimate goal. I just had the idea in the shower and wondered if I could do a quick prototype.

    • #html
    • #css
    • #javascript
  • 2 weeks ago
  • 5
  • Comments
  • Permalink
  • Share

Using Rake, Pow, and TextExpander for Project Templates

TL;DR: I made a Rakefile to automate the creation of a project template that pulls fresh copies of either Twitter Bootstrap or the HTML5 Boilerplate from GitHub. I serve the template’s HTML with Pow, and I use TextExpander fills to generate boilerplate snippets.


Over the years, I’ve put together a number of project templates, each containing its own set of default HTML, CSS, and JavaScript that I would—invariably—abandon. Each would start off with the best intentions, but I’d fail to routinely update them. They’d grow stale, my workflow would change, and I’d start again.

This cycle repeated itself again recently as I started to move back to Web development in my spare time. Wanting to try out some responsive design techniques, I grabbed a copy of the HTML5 Boilerplate project, tweaked it, added some media queries, and posted it to GitHub. I deleted the repository yesterday because I realized that keeping my template in sync with the HTML5 Boilerplate’s releases would be tedious. Thinking about the problem differently, I turned to Rake, and I’m pretty happy with the results.

Workflow

These days, when I start a project, shortly after some sketching but before I even think about what back-end technology will be powering the site, I focus on building the interface using plain old HTML. My default directory structure looks like this:

I like to use CoffeeScript with Jitter, so I include directories named /coffee and /js. Everything else is pretty straight-forward: /css for CSS, /images for images, and a /resources directory for storing things like PSD files, icon sets, and other project-specific clutter. Finally, the /docs directory is for annotated CoffeeScript documentation that’s generated with Docco.

I create an empty file called application.coffee in the /coffee directory, which ends up compiled to application.js in the /js directory. I also include an empty application.css file in the /css directory. Finally, I toss in an empty index.html file.

If I use a framework like the HTML5 Boilerplate project or Twitter Bootstrap, I download the package and place the project’s various assets into the appropriate directories. The HTML5 Boilerplate’s index.html becomes the default index file when I use that project.

With all of the files in place, I initialize an empty Git repository and start cranking out code. But there’s an easier way.

Rake

This file handles all of the above for me by providing three command-line options.

$> rake newblank

This creates the blank project directory structure and a handful of empty files as outlined in the Workflow section above (complete with a Git repository).

$> rake newhtml5

This clones a copy of the HTML5 Boilerplate project, places its files in the proper directories, and creates a new Git repository.

$> rake newtwitter

This clones a copy of the Twitter Bootstrap project, moves the JavaScript and image assets into the proper directories, compiles the .less files into a single CSS file, runs a quick find-and-replace on the compiled CSS to change references to ../img into ../images because I’m tightly wound and like to name my images directory /images, and creates a new Git repository.

To use it, create a directory for your project and place the contents of this Gist into a file in that directory. Name the file Rakefile. Then, cd into your project’s directory and run one of the above commands.

Advantages

I don’t have to keep my template in sync with changes to projects I use (e.g., the HTML5 Boilerplate project). I don’t have to keep a blank project template full of empty files and directories lying around that will grow stale and require maintenance. I always get the latest HTML5 Boilerplate and Bootstrap code when starting a new project. Everything’s boiled down to one file that’s far easier to maintain and tweak as my needs change. And if a new set of fancy boilerplate comes out, all I have to do is write a new Rake task to add it to my arsenal.

Pow

You can use Pow to serve the flat HTML files you create using any of the templates that are generated by this Rakefile.

Create a directory for your project, and then create a public directory inside your new project’s directory. Place a copy of the Rakefile in the public directory. It should look like this:

cd into the public directory, and run one of the commands to generate the template structure. Then—just like you would with any other Pow-based project—create a link to your project’s directory (not the public directory, but the root project directory) in ~/.pow. For more info on using Pow, see the user’s manual.

Yes, you could just open your plain old HTML files in a browser without having Pow serve them, but using Pow lets you avoid addressing your assets (images, JS, CSS) with relative paths. You won’t have to go through your code and change all the relative paths to full paths once you’re ready to turn your templates into production code.

TextExpander

I love TextExpander, and I use it to fill a gap that’s left by generating blank files with no template code in them. For example, I like my default application.coffee file to include the following header:

#      Project Name v1.0
#      (c) 2012 Company Name
#      http://projecturl.com

# Load the application once the DOM is ready using a `jQuery.ready` shortcut.
$ ->

This block turns into a very pretty header when I run Docco to create my documentation, and it sets the application up to work with jQuery. I created a TextExpander fill to generate this header. The fill, which is triggered when I type coffeehead, prompts me to enter the project name, version, company name, and project URL. For more info on how fills work, see this video by the venerable Merlin Mann.

I have a similar fill that creates the header for my CSS files, which looks like this:

/*
      Project Name v1.0
      (c) 2012 Company Name
      http://projecturl.com
*/


/*  Header
--------------------------------------------- */

This one’s triggered when I type csshead. It’s very similar to the CoffeeScript header. Another fill creates CSS section breaks by prompting me for the name of the section when I type csssec:

/*  Section
--------------------------------------------- */

If you have TextExpander and want to try these snippets for yourself, you can download a copy of them here.

Bonus: Docco

Don’t delete the Rakefile when you’re done generating a new project! It provides a task for creating annotated documentation for your CoffeeScript:

$> rake doc

Run that command, and then check the contents of the /docs directory.

Requirements

I’ll be honest; I lost track of all of the software that’s required to make this work. You’ll need Ruby and Rake and Git to get started. To compile the .less files that come with the Twitter Bootstrap project, you’ll need Node.js and NPM. Once you have NPM installed, you’ll need to install the less package. You can also install CoffeeScript and Docco with NPM; Docco also recommends installing Pygments for syntax highlighting. If I missed any other requirements, please let me know in the comments.

    • #git
    • #coffeescript
    • #javascript
    • #css
    • #html
    • #rake
    • #docco
    • #html5boilerplate
    • #twitterbootstrap
  • 3 months ago
  • 12
  • Comments
  • Permalink
  • Share

The Markup

This is part three of what has spontaneously become a series.

Part 1: Writing Modular and Reusable CSS

Part 2: HTML5 and IE8

In part one, I neglected to include any HTML because I wanted to focus specifically on the CSS. But without looking at the HTML, the niftiness of the CSS is lost.

Here, then, is a quick look at why using classes (rather than IDs) makes for easier maintainability, and how writing element-agnostic classes makes our CSS reusable.

Classes vs. IDs

Suppose we had created the profile box with a div using an ID instead of a class. Convention says this is acceptable since the profile box is only intended to appear once on each page—it’s unique.

    <div id="profilebox">

The CSS would have looked like this:

    #profilebox img, #profilebox h3, #profilebox p { float: left; }

    #profilebox img { margin-right: 10px; }

    #profilebox h3 {
      margin: 0 0 10px 0;
      width: 150px;
    }

    #profilebox p { font-size: 1.3em; }

    #profilebox .profile_button {
      float: right;
      margin: 0;
    }

Great! Now we have to create the list of people in the Following box. Since the list contains multiple items, it makes sense to use a class.

    <ul>
        <li class="following"><img src="http://placehold.it/30x30" alt="Profile Picture" /><p><a href="#">Jane Doe</a></p></li>
        ...
        ...
    </ul>

And the CSS would have looked like this:

    .following { margin-bottom: 10px; }

    .following img, .following p {
        display: inline;
        vertical-align: middle;
    }

    .following img { margin-right: 10px; }

    .following p { font-size: 1.3em; }

We start to see the first problem: there’s overlap between our following class and our profilebox ID.

    .following img { margin-right: 10px; }
    #profilebox img { margin-right: 10px; }

    .following p { font-size: 1.3em; }
    #profilebox p { font-size: 1.3em; }

The second problem is a bit hidden. Our designer comes back after we’ve completed the first draft of the CSS and says, “Ten-pixel gutters on images are out. Twenty pixels is the new hotness.”

We’ve declared two instances where this will have to be fixed:

    #profilebox img { margin-right: 10px; }

    .following img { margin-right: 10px; }

If we continued to code in the same fashion, the profile pictures in the review timeline would have presented a third instance that would have to be changed. Our solution in part one gets around this by using a single class for both elements and defining the image gutters once.

On Classing Specific Elements

Suppose we had written the CSS for our itembox class by targeting a specific element (in this case, the div).

    div.itembox img, div.itembox h3, div.itembox p { float: left; }

    div.itembox img { margin-right: 10px; }

    div.itembox h3, {
      margin: 0 0 10px 0;
      width: 150px;
    }

    div.itembox p { font-size: 1.3em; }

    div.itembox .profile_button {
      float: right;
      margin: 0;
    }

Not only would we have added 21 additional characters to the file, we would have made it impossible to reuse the class on the list items in the Following and Trending boxes. The solution that we came up with in part one was much more flexible because it was element-agnostic.

    • #css
    • #html
  • 10 months ago
  • 5
  • Comments
  • Permalink
  • Share

HTML5 and IE8

The example project I put together for the article I wrote on OOCSS is incomplete, and it’s bothering me. This article will address one glaring oversight: support for IE8.

Why Care?

IE8 is a big target. Depending on who you ask, IE8 controls over 30% of the market, while IE6 and IE7 each have less than 10%. IE9’s adoption rate has been slow as well with less than 25% of Windows 7 users claiming it as their primary browser.

Given IE8’s prominence and IE9’s slow adoption rate, it behooves us to make sure our layout doesn’t look janky in IE8.

What’s Currently Wrong

Here’s what the Twitter for Movies layout looks like in IE8:

Not pretty. The reason for the busted layout is simple, though: IE8 doesn’t support several HTML5 elements, including the section, header, and footer tags that we used in this layout.

Adding support for those tags is easy.

Modernizr

Modernizr is a JavaScript library that magically adds support for certain HTML5 elements to IE6-8. A quick visit to the Modernizr download page, and we have a copy of the library that we can link into our head tag.

    <script type="text/javascript" src="modernizr.js"></script>

To enable Modernizr, we also need to change our html tag from this:

    <html lang="en">

To this:

    <html lang="en" class="no-js">

That’s it! Sorta. Here’s what our layout looks like now:

What gives?

Well, Modernizr adds support for the HTML5 tags we’re using, but it doesn’t set any default display properties. Safari, Chrome, and IE9 treat the section, header, and footer tags as block-level elements by default, but even with Modernizr, IE8 doesn’t. The fix is simple; add this line to our CSS file:

    header, section, footer { display: block; }

And here’s the result:

Drawbacks

It’s 16k of additional code that your users have to download. The overall goal of the OOCSS tutorial was speed, which you gain through shorter selector chains, reusable classes, and smaller CSS files. Smaller downloads mean faster page loads. Adding another 16k of code—which is still quite small!—runs contrary to the purpose of the original article.

The good news is that you can accomplish the same thing with about 4k of code using the html5shim library, which is the magic part of Modernizr that adds support for HTML5 tags in IE.

That said, Modernizr does a lot more than just give us a few new elements to work with, and if you take full advantage of the library’s features, the extra 12k is worth the download.

UPDATE: This has turned into a three-part series. The next installment discusses the HTML used in this demo.

    • #html5
    • #css
    • #ie
  • 10 months ago
  • 4
  • Comments
  • Permalink
  • Share

Writing Modular and Reusable CSS

When I heard Nicole Sullivan talk at CodeConf back in April, I was intrigued by the case study she did while working at Facebook.1 I’ve wanted to try a similar approach to writing CSS for quite some time, but I’ve yet to work on a project where high-performance, modular CSS was a priority.

So I’m writing this tutorial. I want to see object-oriented CSS (OOCSS) in practice; if you’re interested, too, follow along.

The rest of this article assumes at least some familiarity with CSS and object-oriented programming concepts.

Our Project

It’s Twitter for movies! [obligatory groan] The design we’ll be working on is for a fictional movie review site that lets you post pithy remarks about films you’ve seen. Here’s a very basic wireframe.

To get started, let’s dissect it from a high-level.

Commonalities

Modularity implies that we need parts of a page that can be treated as discrete elements. But we also want our CSS to be abstracted enough that it can be reused for multiple elements. In looking at this (very) basic wireframe, we can already see some parts of the page that are similar.

As the wireframe transitions to a mockup, the added fidelity lets us spot even more commonalities.

And if you’re a bit flexible in defining similarities, you’ll see that certain parts, like the Following box and the Trending box, are identical (save for the alignment of an image or two).

Writing the Code

Nicole Sullivan recommends keeping your selector chains short. The shorter the selector chain, the faster the browser can parse your CSS. There are technical reasons for this, but that goes beyond the scope of this article. If you’re interested, you can read the nitty-gritty details at Google Code.

Suppose you want to target the star ratings in the review boxes. You could use something like this:

section#reviews div.review div.rating { ... }

But—assuming you aren’t using the .rating class anywhere else—you could safely shorten it to:

div.rating { ... }

The div part isn’t necessary for this selector either since we want the .rating class to be reusable and extendable. So, simplify it:

.rating { ... }

Now, if we want to write exceptions to this rule, we can target specific elements that have this class applied to them.

span.rating { ... }

Breaking It Down

First, let’s identify which parts of the page are similar enough to be grouped together into a single CSS rule. In object-oriented-speak, we’re defining a parent class or parent object.

The profile, trending, following, and review boxes all contain similar elements.

We’ll start with the profile box.

Note: If you want to skip ahead, I’ve posted all of the code for this project on Github. There’s also an online demo.2

The CSS

The parent class for all of these objects will be called .itembox. This isn’t terribly semantic, but the descriptor has to be generic, as it describes an item that can contain a link to a movie, a person’s profile, or an entire movie review.

Here’s the CSS for the user profile in the profile box:

.itembox img, .itembox h3, .itembox p { float: left; }

.itembox img { margin-right: 10px; }

.itembox h3 {
  margin: 0 0 10px 0;
  width: 150px;
}

.itembox p { font-size: 1.3em; }

.itembox .profile_button {
  float: right;
  margin: 0;
}

The .itembox class contains several elements, including images, an H3, and a paragraph tag.

Now that we have our default parent object defined, we can extend it (i.e., subclass it). Here’s the CSS for each user in the Following box:

.itembox.following { margin-bottom: 10px; }

.itembox.following img, .itembox.following p {
  display: inline;
  float: none;
  vertical-align: middle;
}

Just as with object-oriented programming, the items in the Following box inherit from the parent class .itembox and override functionality where necessary. In this case, we’re extending the parent class by adding a bottom margin to the row and adjusting the layout of images and paragraphs that appear in each row.

Creating the movie list in the Trending box is pretty straight-forward:

.itembox.trending {
  font-size: 1.2em;
  margin-bottom: 5px;
}

Again, we’re just overriding the defaults that were established in .itembox.

Finally, here’s how we create each row of the review list:

.itembox.review { margin-bottom: 20px; }

.itembox.review p { margin-top: 8px; }

.itembox.review h5 { margin-bottom: 2px; }

The movie reviews contain a few extra elements. Specifically, the title is an H5, and we’ve included rating stars. These features are necessary for the review subclass, but they might also end up being useful for future iterations or subclasses of the main .itembox class, so let’s update the parent class with these features.

.itembox img, .itembox h3, .itembox h5, .itembox p { float: left; }

.itembox img { margin-right: 10px; }

.itembox h3, .itembox h5 {
  margin: 0 0 10px 0;
  width: 150px;
}

.itembox h5 { width: 580px; }

.itembox h5 span { font-weight: normal; }

.itembox p { font-size: 1.3em; }

.itembox .profile_button, .itembox .stars {
  float: right;
  margin: 0;
}

That’s it! Four discrete page elements constructed with about 26 lines of CSS.


Writing good CSS starts with being able to see the constituent parts of a page—where the boxes are. One way to get good at this is to use the Web Developer Toolbar for Firefox. It allows you to outline all block-level items on the page, which looks like this:

But good CSS requires more than spotting boxes. As @stubbornella puts it, it’s about pattern recognition. In our example above, we noticed the box pattern that included images, some descriptive text, and a couple of links. These things might not always appear in the same order (or at all), but they always appear in the same group.

After this exercise, I’m an OOCSS convert. It took less than 8 kilobytes of HTML and CSS to construct a reasonably complex layout. That’s pretty impressive, and—looking at it now—it could probably be simplified even further. Figured out a way to streamline it? Leave a note in the comments.

If you’ve found this intriguing and want to read more about OOCSS, have a look at the project’s FAQ on Github.

View a working demo of the example project.

View the example project’s source code on Github.

UPDATE: I’ve written a follow-up article on how to add IE8 support to this project, and an additional post discussing the HTML used to create this demo.


  1. Check out this presentation. Slides 36-42 are great and pretty self-explanatory. ↩

  2. You’re going to want to use a modern, standards-compliant browser to view this. Safari, Chrome, IE9, and Firefox 4 are all safe bets. ↩

    • #css
    • #oop
    • #oocss
  • 10 months ago
  • 3
  • Comments
  • Permalink
  • Share

Learning HTML & CSS

Jumping into HTML and CSS can be intimidating, mostly because the newest specifications for each—HTML5 and CSS3—are evolving at the same time that they’re being put into practice. A lot of the choices made in the development of these new specifications are based on the need for more semantic markup and less reliance on graphic design and animation software like Photoshop and Flash.

Semantic markup? Graphic design and animation?

Yup. Intimidating.

It used to be that a guy or gal could sit down with his favorite browser, open his favorite Web site, and view source to figure out how to build a page with HTML. In the simpler times when I learned HTML—in 1995—Web pages were mostly hand-coded by humans. The source was readable. These days, content management systems and blogs and a torrent of technologies have muddied the HTML source of most sites into an auto-generated hodgepodge of holy-crap-this-is-unreadable markup.1

Learn Before You Learn

There are a couple of things you should know before creating your first Web page.

  1. Web standards are important.
  2. Accessibility is important. This is an extension of #1.
  3. HTML is for structure. CSS is for presentation.

Keep these things in mind when you read through the tutorials and books below.

Start Simple

Rather than starting with the inner workings of HTML5 and CSS3, focus on the basics.

The venerable Web Monkey has a great tutorial explaining how to create your first HTML document. The almost equally venerable Sitepoint has an expansive tutorial on HTML and CSS that covers tools, file organization, and more.

If you’re willing to spend a few quid to get your learn on, Think Vitamin offers a subscription for $25 per month that gives you access to a wide selection of video-based courses, including a series on both HTML and CSS.

I also recommend picking up Jeffrey Zeldman’s Designing with Web Standards. It’s long, but you’ll walk away from it with a proper appreciation for Web standards that will form a solid foundation for future work. It’s worth it.

Next Steps

Now that you understand the basics, start digging into the newer specs.

HTML5

  • Building Web Pages With HTML5 at Web Monkey
  • Designing an HTML5 Layout From Scratch at Smashing Magazine2
  • Mark Pilgrim’s beautiful Dive into HTML5
  • HTML5 for Web Designers by Jeremy Keith from A Book Apart ($18)

CSS3

  • Get Started With CSS3 at Web Monkey
  • CSS3.info’s collection of CSS3 features that have been implemented in at least one of the major browsers (along with info about how to start using these features now)
  • CSS3 for Web Designers by Dan Cederholm from A Book Apart ($18)

I can’t say enough nice things about the books from A Book Apart. Both are short (less than 100 pages) and written with wit and humor. They also offer eBook versions for $9 that are compatible with iBooks.

Getting Help

Searching for help with HTML and CSS problems using Google can be painful. Not only will you have a hard time finding answers because of all the content farm spam, but the answers you find aren’t always trustworthy or examples of best practices.

Head over to Stack Overflow and run your search there instead. Or have a look at questions that were tagged with html5 or css. If you can’t find a solution, post your question. The Stack Overflow community is large and full of pros that are willing to help out.

Information Overload

This is a lot of stuff to take in, especially if you decide to read all three of the books listed above. However, you can probably learn enough in a weekend to start cranking out reasonably awesome pages. So caffeine up, open a tutorial, get excited, and make something.3


  1. And often, the auto-generated markup created by content management systems ignores semantics entirely. ↩

  2. This article also touches on integrating CSS3 and is a good example of separating presentation from structure. ↩

  3. I sorta stole that line from a t-shirt. ↩

    • #html
    • #css
    • #primer
  • 1 year ago
  • 3
  • Comments
  • Permalink
  • Share
Renaissance Nerd is a collection of links and articles cobbled together (and sometimes written) by Jeff Mueller.

Pages

  • About

Elsewhere

  • @jeffmueller on Twitter
  • jeffmueller on Pinboard
  • jeffmueller on github
Clockpunch: Log time. Track Stats. Stay On Budget

I made an iOS app called Clockpunch. It's for tracking your work. Sales go toward making Renaissance Nerd possible.

  • RSS
  • Random
  • Archive
  • Ask me anything
  • Mobile
Powered by Tumblr

Renaissance Nerd is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. Effector Theme by Carlo Franco.