Article Archives

Magic Numbers in CSS

Despite the super fun sounding name, magic numbers are a bad thing. It is an old school programming term for "unnamed numerical constant". As in, just some number plunked into the code that is probably vital to things working correctly but are very difficult for anyone not intimately familiar with the code to understand what it is for. CSS is loaded with unnamed numerical constants, but they are usually paired with properties and in the context of a selector so there is little mystery. There are magic numbers in CSS though, and they are still bad.

(more…)

WP Migrate DB Pro

I think the most common tech question we get on ShopTalk show is how to keep a WordPress database in sync between live and local. This (paid) plugin can do it right from one admin screen to another by POSTing secure requests of SQL data bit by bit until they are in sync.

Line-On-Sides Headers

Forums user McAsh wondered how they might code up a design in which there was a large header and a smaller subheader beneath it which featured double horizontal lines jutting out after the text to both the left and right of the centered text. An easy thing to mock up as image, but a much more difficult thing to pull off in CSS because of the variable nature of text (length, size, etc).

(more…)

csscss

A CSS redundancy analyzer that analyzes redundancy.

Gives you output like:

{.contact .content .primary} and {article, #comments} share 5 rules

If you have multiple selectors sharing five or more rules (properties with the same value), that's likely a good opportunity for optimization (combine into new class or comma separate selectors elsewhere).

Someone should make a hosted version where you just drag-and-drop a .css file to analyze.

Can You “Over Organize” JavaScript?

There's no question that on sites with lots of JavaScript, you need a strict organizational pattern to keep everything making sense and the code approachable. I've mentioned in the past I like grouping things into individual files each containing a functionality-specific object literal. Taking things a wee bit further, we can be strict about this pattern and make sure we group together all sectors in one place, all "init" functions in one place, all event binding in once place, and have the rest be little well-named mini functions that do very specific things.

I wonder though, is this too organized?

(more…)

CSS-Tricks Chronicle XII

I'm hard at work creating a brand new talk I'm so far calling "CSS is for Computers" that I plan to be giving and refining at some upcoming conferences.


There is a whole new series in The Lodge. Even if you aren't interested in the content of the lodge, but are interested in supporting CSS-Tricks, being a Lodge member is the best way to do that. As a thank you, you now don't see any ads no matter where you are on the site as a logged in Lodge member.

I'm still brainstorming new ideas for more Lodge content. My best idea so far is "Deep Dive" videos where posts/almanac entries/snippets/etc will have optional videos attached to them where the content is explained in more detail. Those videos will only be watchable by Lodge members. Just an idea.


CodePen is humming along! New features for all users include making auto-run JavaScript optional, making the Hire Me button for everybody, editor layout alternatives, and upgrading the editor as a foundation for many more editor improvements. PRO users now have asset hosting.

You'll want to stay tuned to CodePen. Tons more to come.


Lots of great conversations on ShopTalk lately including Brandon Mathis, Alex Sexton, Samantha Warren, and Lara Swanson.

There is a new feature on the ShopTalk website as well. Dave created Time Jump - a JavaScript plugin for deep linking times in podcasts. You can now link to specific times with a query string or hash, like:

http://mypodca.st/first-episode/?t=1h23m45s
http://mypodca.st/first-episode/#t=23:45

To give it a spin, check out this time jump link to a very important question.

If you've never listened to ShopTalk, we also now have a master archives page to help you find episodes you might be interested in checking out.


Also new on ShopTalk, we now have ladies cut T-Shirts in The Store!


My latest Pastry Box Project entry was about introversion. It seemed to resonate pretty strongly with a lot of folks. I did a follow up article on my personal site with some of the reactions and further thoughts.


I'm moving to Milwaukee soon! It took me a while to find a place but eventually being vigilant on Craigslist panned out. Why Milwaukee? I have a bunch of friends there I visit fairly often and I always love it. I grew up in Wisconsin, but never lived in Milwaukee. Heading back to Wisconsin means being closer to family and old friends, which I like. Plus it's a lot less expensive than living in the San Francisco area, and I could use the savings as I'm out on my own trying to build a startup.

Looking forward to checking out Bucketworks and Lounge 42.


You may have noticed I replaced one of the rotating ads on the site with an ad for my tech alma mater Wufoo. I'm happy to have them as an advertiser because of course I still dearly love the product. For those that don't know, it's a very powerful (yet easy to use) online form builder.

You may have also noticed they sponsored the RSS feed for a few weeks there. I'm going to start doing that as there is demand for it. There are around 108,000 RSS readers, so if you want to run an ad in there, get in touch.


The latest edition of Appliness ("the first digital magazine for web application developers") features an interview with me!

Blink

Chrome is going to use "Blink" as a rendering engine now, a fork of WebKit. I imagine the Chromium team will stop committing back to WebKit, so that project will stagnate a bit. Safari is already rather slow to update, and iOS only allows WebKit on browsers, so that's a bit of a bummer. Overall it's probably a good move and keeps Chrome charging forward. No more vendor prefixes, they say.

Pop Hovers

POP has these cool hovers in the boxes that make up their homepage. The boxes have a white background by default, and as you hover over them a dark background slides up behind, the text colors change, and the text "pops" up a little. When you hover off, the dark background slides away, the text colors change back, and the text pops down a little. I thought I'd try and replicate it because, you know, eff yeah hovers.

Demo

Check out this Pen!

HTML

Each area is a "box":

<a href="#" class="box">
  <h2><span>Breaking news -</span> hippos are sorta dangerous</h2>
  <h3>Tonight at nine</h3>
</a>

CSS (backgrounds)

The styling of the default box is trivial. The hovers are the interesting part. POP does the background slide by using an actual element they animate the position of. If we're OK with this feature only working on browser that support gradients, we can ditch that element and just animate the background-position.

A top-half-white and bottom-half-black background is easy:

background: linear-gradient(
   white, white 50%, black 50%, black
);

Then we make it twice as tall as the element itself:

background-size: 100% 200%;

Like this:

In reality, we'll make the background a little bit taller than 200%, because right at 200% it was exposing a little bit of background into the element still (in Chrome).

.box {
  background: linear-gradient(
     white, white 50%, #333 50%, #333
  );
  transition: all 0.2s ease;
}
.box:hover {
  background-position: 100% 100%;
}

CSS (colors)

The default text color is black, so no CSS needed at all there. On hover, we adjust the colors. The span changing is just a fun surprise and brings more pop to the party.

.box:hover h2 {
  color: #48ad26;
}
.box:hover h2 span {
  color: white;
}
.box:hover h3 {
  color: #999;
}

CSS (bumping)

The tricky bit here is that the "bump" happens in different directions depending on if it's a hover-on or hover-off. The fact that the text moves a bit and then back to it's original position means a transition won't help us here either, this is animation territory. We'll make one @keyframes for the up-bump and another for the down bump. Just a bit of padding will help us, because our box-sizing choice keeps the height of each box the same.

@keyframes up-bump {
  0% { padding-top: 2em; }
  50% { padding-top: 1.5em; }
  100% { padding-top: 2em; }
}
@keyframes down-bump {
  0% { padding-top: 2em; }
  50% { padding-top: 2.5em; }
  100% { padding-top: 2em; }
}

By default (triggers on hover-off) the .box will get the down bump and the :hover will get the up bump. This matches the direction of the background sliding in and out.

.box {
  animation: down-bump 0.4s ease;
}
.box:hover {
  animation: up-bump 0.4s ease;
}

Initial bump fix

Adding that animation on the initial state makes it run right away on page load. Could be a neat effect, could be annoying. The POP site doesn't run them on load. Matt Boldt had the good idea of adding the out-bump when the hover out occurs only (via a class) so it won't run at first.

Check out this Pen!

On no-hover devices...

They are links and no vital content is hidden, so no big deal.

SVG Patterns Gallery

Using SVG for background patterns is great because they 1) are very small 2) are vector, thus crisp at any screen resolution and 3) work in IE 9 (unlike gradients). Gallery by Philip Rogers.

The State of Spinners

If you need to indicate "please wait, something is happening" on a website, a spinner has long been the go-to choice. Probably an animated GIF, although there are other options like CSS animations, apng, SVG, or canvas. James Padolsey goes through each of the possibly options and explains the good and bad as well as introduces a cool new tool.

Slide In (as you scroll down) Boxes

I was playing with my new Nexus 7 (I really wanted to own a real Android device) and I noticed a neat little effect in the Google+ app that comes with it. As you swipe down, new modules of content slide up into place. Video is best here:

(more…)

Printing the Web

Hans Christian with the state of web printing. All the old classics are still important, like display: none; on irrelevant stuff (like navigation) and using pseudo elements to display the URL's of links. But there are new kids on the block like @page which helps you style individual printed pages and control printing orientation for certain elements, -webkit-print-color-adjust: exact; for printing background colors/images, printing crop marks, and preventing widows.

Line Number Mapping for Sass in Chrom Dev Tools

I've always wanted to get this going since seeing this Lennart Schoors post, but this Lee Mallabone tutorial finally pushed me to do it. The debug settings are specific to Rails, but if you're a CodeKit users you probably just do this.

In the past I've thought: I don't need no line number mapping! My SCSS is so organized and modular I can always jump right to what I need to edit. But I could smell defensiveness and stale attitude as I thought it, so here's to being open minded and giving ourselves better tools.

Hang On Placeholders

I remember when the behavior for placeholder="" text on inputs and textareas made that subtle functionality change in WebKit where the text would remain in place until you started typing rather than disappear on focus of the empty input. I think it may have been first on iOS actually, but now both stable Chrome and Safari do this.

I also remember thinking it was a smart change. Of course the placeholder is no substitute for a real

However, Jeremy Keith points out some research by Markus Earnst that suggests leaving the placeholder in place breaks some expectations and causes problems:

It seems that a relevant number of users do not even try to start typing as long as the placeholder text remains visible.

Granted, the research was a bit limited in scope, but it makes sense.

Jeremey provides this CSS solution if you want the old behavior back in WebKit based browsers:

[placeholder]:focus::-webkit-input-placeholder {
  color: transparent;
}

This is me chiming in with a possible best-of-both worlds middle ground:

[placeholder]:focus::-webkit-input-placeholder {
  transition: opacity 0.5s 0.5s ease; 
  opacity: 0;
}

The second time value in that transition means "wait half a second before firing off this transition." I suspect that some people click or tab to inputs to get ready to enter information before they are cognitively ready to pay attention to that input yet. But once the focus takes place, then they start paying attention. If we give them a half a second where the placeholder is still visible and another half a second to fade it away, that is likely enough for them to understand the hint that the placeholder was giving them.

The event timeline being:

  1. User clicks (or taps, or tabs to, or whatever) the input
  2. Their eyes move to the input and their mind starts paying attention to it
  3. They comprehend the placeholder hint
  4. Placeholder goes away

A demo of that and another variation where the placeholder slides away toward the label:

Check out this Pen!

For the record, I'm not saying this is absolutely better. There is no hard science here. I'm just proposing an alternate UI experience that seems to make sense to me.

Are there any other solutions we could explore?

There’s more to the CSS rem unit than font sizing

The following is a guest post by Roman Rudenko, a mad scientist at Mobify where he’s tasked with understanding why browsers misbehave and with cajoling them into playing nice. When he’s not coding, Roman is learning to ride a motorbike without crashing into too many solid objects.

Many web designers and developers are familiar with the CSS rem length unit. But, you may not know that it has a couple of handy alternate uses. In this post, I’ll describe how to use the CSS rem unit to scale specific page elements while leaving others unaffected. I’ll also discuss how to use it as a replacement for the under-supported vw (viewport width) unit.

For readers unfamiliar with the rem unit (standing for "root em"), it provides a way to specify lengths as fractions of the root element’s font size. In practical terms, this almost always means the font size of the <html> element. The most obvious use for rem is replacing em to protect inner element font sizes from being changed by outer elements, thus avoiding the classic nested em scaling problem. But rem effectively operates as a custom adjustable unit, so it can be useful for other things too.

First, let’s look at how rem works and how it differs from the em unit. An em value is calculated against the font-size of a current element, so boxes sized with it will consequently scale as font sizes are adjusted by the element or its ancestors. Meanwhile, rem is defined as the font-size of the root element. So, all references to rem will return the same value, regardless of ancestor font size. In effect, rem is a document-wide CSS variable. Browser support for rem is quite good these days. It’s limited on desktop because IE8 does not support it, but common mobile and tablet browsers handle it much better.

Rem can be used for its typical font sizing duty. When markup nests in complex ways, font-size declarations with em values may compound unexpectedly, and rem is a good choice for untangling those issues. However, there are some other interesting uses of rem.

Scaling document elements

You can use rem to scale some elements in a document while leaving others in place. In this example, the font-size of secondary page content (slideshow controls, illustration names, post metadata) is controlled via rem, but the primary content remains sized in pixels.

Check out this Pen!

When one of the red size adjustment links is clicked, a small piece of JavaScript adjusts <html> font-size, resizing secondary elements without altering primary ones.

This style of sizing can be useful for user-driven customization, or to adapt layouts for cases that require secondary elements to be more touchable (tablet) or visible (TV). Without rem, every adjustable element would have to be resized separately.

/* States */
html.secondary-12px { font-size: 12px; }
html.secondary-14px { font-size: 14px; }
html.secondary-16px { font-size: 16px; }

/* Primary content stays fixed */
body { font-size: 18px; }

/* Secondary content scales */
.post-inner .meta { font-size: 1rem; }
.figure .title { font-size: 1rem; }
.slideshow .controls { font-size: 1.25rem; }
.slideshow .controls a { padding: 0 0.5rem; }

Replacement for vw

The CSS vw unit is defined as 1/100th of viewport width. This unit is useful for avoiding compounding in width calculations, just as rem avoids font-size multiplier compounding. It can also be used for non-width properties, such as font-size (fitting a fixed fragment of text into a percentage-sized box) or height (preserving element aspect ratio). Support for vw is still spotty. So, we can use rem instead and dynamically recalculate <html> font size to match vw unit size.

Let’s have a look at an example implementation for this workaround (resize browser to see adjustments):

Check out this Pen!
body { font-size: 12px; margin: 0; padding: 0;}
.one, .two {
  border: solid #666;
  border-width: 10px; border-width: 0.01rem;   /* 1vw */
  border-radius: 30px; border-radius: 0.03rem; /* 3vw */
  font-size: 20px; font-size: 0.02rem;         /* 2vw */
  padding: 20px; padding: 0.02rem;             /* 2vw */
}

Here, the <body> element font-size rule insulates content from changes in <html> font-size. Browsers that don’t understand rem are given a pixel-based fallback; browsers that do know rem derive the proper dimension from <html> font size.

An earlier version of this example allowed browsers that recognize the vw property to use it directly, but that was pulled after Chrome 25 failed to apply a border width specified with vw. Rem-based ersatz replacement had no such issue.

It was possible to do all of this before the rem unit was available by computing and assigning properties directly with JavaScript. But, rem makes things much easier. With rem, there’s only one assignment to make for the entire document, and the script doesn’t need to remember which properties should be scaled in what exact manner.

(function (doc, win) {
    var docEl = doc.documentElement,
        recalc = function () {
            var clientWidth = docEl.clientWidth;
            if (!clientWidth) return;

            docEl.style.fontSize = clientWidth + 'px';
            docEl.style.display = "none";
            docEl.clientWidth; // Force relayout - important to new Android devices
            docEl.style.display = "";
        };

    // Abort if browser does not support addEventListener
    if (!doc.addEventListener) return;

    // Test rem support
    var div = doc.createElement('div');
    div.setAttribute('style', 'font-size: 1rem');

    // Abort if browser does not recognize rem
    if (div.style.fontSize != "1rem") return;

    win.addEventListener('resize', recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);

There are a few things to note in the above JavaScript. First, the script will terminate early if the browser is out-of-date and doesn’t support the addEventListener API or the rem unit itself. Second, instead of setting <html> font size to an actual vw unit, it’s set to the viewport width in pixels. This means the CSS would need to scale vw values by a factor of 100 for use with rem, but avoids rounding bugs that would otherwise arise due to the limited font-size precision in Webkit.

Other viewport units can be supported in pretty much the same way. There are downsides to this approach. For instance, you can’t use rem for other purposes. And, you can only make use of one viewport unit (vw) at a time and so can’t use others like vh, vmin, or vmax.

While almost no production browser today supports true CSS variables, quite a few let you cheat a bit and get one in the form of the rem unit. If you don’t need to use rem for normal font sizing, you can use it for runtime scaling of pretty much anything. If you must use rem for font sizing, you have the option of using CSS preprocessors (Sass or Less) to compute proper font dimensions, leaving the rem unit free for runtime trickery.

Tricky Textarea Pulltab

In desktop Safari, Chrome, Firefox, and Opera-under-Presto, (not IE, not mobile anything) <textarea></textarea>s have a little resizer nugget in the bottom right corner. Textareas are for writing in, so if users need more space to feel more comfortable writing in there, they can have it. Clicking and dragging that resizer literally changes the box model of that textarea, pushing other things away as needed. We can use that little ability to make a trick!

(more…)

Automatic Table of Contents

Any long page of content with distinct and well marked up content can benefit from a table to contents. A table of contents provides a quick way to jump down the page to the desired section. Of course you can create a table of contents manually, but it may be smart to build it dynamically on-the-fly with JavaScript. (more…)

Finer Grained Control of Hyphenation

David Storey shows off the latest work-in-progress CSS Level 4 stuff for hyphenation. Like properties to make sure multiple subsequent lines don't hyphenate ("ladders"), how many characters need to be left on the old line and new line, and what character to hyphenate with.

Learn CSS Layout

Learn by seeing examples and code together in an easily digestible page-by-page format. Works on screens large or small, which we all know is darn important these days. By Greg Smith and Isaac Durazo.

Responding to Voice

Jordan Moore experiments with talking to the browser to adjust how things look. For instance, "Make the text larger." Like in, you know, the future.

CSS-Tricks Chronicle XI

I'm speaking at a few things coming up:

And before that I'll be at LessConf just hanging out.


You may have noticed I stopped cross-posting new episodes of ShopTalk over here. Hopefully nobody thought it was dead because it's going as strong as ever with lots of great episodes lately. I just thought it might have been annoying if you subscribe to both. If you don't — follow @ShopTalkShow on Twitter and/or subscribe in iTunes and you're all set.


The U.S. post office changed their shipping rates this year. So we updated The Store's shipping prices. We charge exactly what it costs us to ship. To the U.S. = $4.90 — Canada is $5.75 — the rest of the world is $11.90.

That goes for the CSS-Tricks store, the CodePen store, and the ShopTalk store.


I'm about half-way through a new series on The Lodge about designing an artist's website from scratch, mobile first, using WordPress as a customized CMS. I'm going to do my dangdest to get it done in March.

Also: the Kickstarter six month subscriptions have expired. I really should have sent out reminders that was coming up, but I didn't. If that was sudden and surprising for you and need a short extension to finish up watching/downloading, please send a note. You can also re-subscribe anytime by logging in and going to the signup page.


I recently attended the second day of W3Conf, and if you didn't notice the flood of blog posts, I liveblogged it. It was a pretty fun way to attend a conference because I had to pay hyper-attention and thus got a lot more out of it than I might have otherwise. Exhausting, though.


We got quite a bit of attention lately for human-readable-izing our Terms of Service and Privacy Policy on CodePen. It's not a totally original idea. I first saw it on 500px. Editorally has a nice one too without the split.


The Almanac has been a long-time not-quite-finished project around here. Most of the pages are done, but there are plenty that are not. I've been plugging away at it still and Estelle Weyl has helped me with some. An offer: if you have any interest in writing up any of the missing pages, get in touch. I'll pay you on a per-page basis to help.

Client-Hints

We all know UA sniffing sucks. But it's really common because there is a real need to know stuff about the browser on the other end when serving up content and resources. What if instead of just a UA string, we got information about the browser in the headers as well? Client-Hints aims to be that. It's in the RFC (Request for Comments) stage now and there is great discussion about what kind of information it should be making available.

Flat UI

Really nice set of user interface elements from the folks at Design Modo. This style is hitting a real design nerve right now. I like how they went the extra mile and made all the components actually work (e.g. sliders and radio buttons and whathaveyou).

The JavaScript is a bit hodge-podge though, using bits of jQuery UI, Twitter Bootstrap, Video.js, and many more. It's open source, so it would be neat to see people chip in and remove some of those dependancies and build a consistant JS architecture beneath it.

Update: Looks like they are having a bit of a copyright spat with LayerVault. Whattyagonnado.

Quotes & Accents

Reminders about what keys to press to get curly quotes and accented characters by Jessica Hische. I'm a major offender (SEE?!). I should be writing in Markdown which automatically fixes it.

Using SVG

SVG is an image format for vector graphics. It literally means Scalable Vector Graphics. Basically, what you work with in Adobe Illustrator. You can use SVG on the web pretty easily, but there is plenty you should know.

(more…)

Uniqlo Stripe Hovers

For the larger promotional boxes in the design of Uniqlo.com, they use animated stripes that reveal on hover. It's kind of awesome, if you ask me. Perhaps because they wanted to share the awesome with as many different browsers as possible, they used an animated GIF to produce the effect. It's fairly small at 4K, but as we know around here, it is also another HTTP request. Let's reproduce the effect in a progressive enhancement style: less browser support but more efficient.

(more…)

Search with Filters Responsive Design Pattern

I've long been interested in design patterns. Common and proven-effective solutions to design problems. Too many settings to display at once and it's confusing the user? Put them into logical groups and use an accordion design pattern! Patterns got even more interesting with the onset of responsive design. How do these patterns hold up as the available screen space changes?

We might be able to get six or more tabs on a laptop screen, but it's only really practical to get three on most mobile devices. What do we do? Perhaps converting them into an accordion would work.

Brad Frost has done a great job in keeping a repository of Responsive Patterns. Brad and Dave and I were sitting around after InControl talking about design patterns that hadn't been explored as much. Dave mentioned "Search with Filters" as an example. There can be quite a lot of UI involved in a search filter, so you have the challenge of displaying that without taking up too much room for the actual results, as well as allowing the user to change those filters without being too disruptive.

On desktop, you can do a split column design with the filters on the left and have plenty of room for results:

On a smaller screen though, you won't have the room to pull off that split panel. You can squeeze down into one column though:

Notice how the title "Search Filters" became an obvious link (just CSS changes). This simple set of filters is already taking up quite a bit of room. Any more complicated and you'd have a full screen of filtering before you saw any results. Probably best to make that a link that hide/show's the filters:

Now the question becomes: how do you access those filters once you've swiped down far enough they are gone? Perhaps you have an infinite scroll of search, which can be a great pattern for something like images. But you've scrolled down quite far and now want to alter the filters. Perhaps once we've scrolled past the filters, we could have a "filter bar" attach to the top of the screen allowing access no matter how far down you've scrolled:

Which can be opened and altered just like when it's at the top of the page:

And that makes a pattern!

But, [insert retort]!

Surely this pattern doesn't cover all possible needs. Design patterns often don't. They are patterns, not dies.

Google Image Search (at least on iOS) has a paginated grid of images so you don't lose sight of the header where you can filter.

Should the fixed bar have the search field in it too? Maybe. What happens if you change a filter and it reveals more stuff? Perhaps scroll them to the first new one it revealed. Perhaps keep their place as closely as you can and visually hint there is new results elsewhere. Wouldn't a "back to top" link work just as well? Maybe. It's all just food for thought.

The Pattern

The tech for this isn't all that fascinating. I'm not sure it warrants a line-by-line CSS analysis. Essentially the two column design is squished into one while a narrow screen media query matches.

The JavaScript to fix the header position is slightly more interesting. I essentially used this "Persistant Headers" technique. Only in that article, the headers were cloned and the clone was shown when needed. I thought that was a bit heavy handed. In this case, the search filter area itself just becomes fixed position. In order to prevent the jump that would happen when an element that used to be "in the flow" becomes out of flow, I measure the height and add padding to compensate.

All the JavaScript, since it's all related to "search", is kept together in a single object which is a simple but nice way to structure JavaScript.


Got an improvement? Another pattern to solve the same issue? Tag it "filtered-search" on CodePen.

Setting a Performance Budget

I read this Tim Kadlec article a while ago but the more I think about it the more I like it.

If you are going to take performance seriously (instead of just paying lip service to it or chipping away at it) set hard limits that your site will not cross. Say something like 300k total page weight, 25 requests, and 100ms response time. Nothing may exceed that. If something does, it's all-hands-on deck to fix it. Treat it like a major bug or downtime. If discussing something new that would cross the line, something else needs to be optimized or removed, or it's not added.

Using WAI-ARIA Landmarks

I need to do a better job at at using the role attribute. It's so easy and has so many benefits. Important note: all content should be within a landmark role. Steve Faulkner shows the way.

icon-closeicon-emailicon-linkicon-menuicon-searchicon-tag