Article Archives

How to Make a Smartphone Controlled 3D Web Game

The following is a guest post by Charlie Walter. Charlie does a bunch of work with Three.js (3D in the browser with WebGL) and gaming concepts. If that stuff interests you, read on!

In this tutorial I'll explain an approach on how to connect your smartphone to a 3D web game. We'll be making a car which you can control by tilting your phone (using the phone's accelerometer). We'll use the JavaScript library three.js for working with WebGL as well as WebSockets through the socket.io library and a few other web technologies.

(more…)

Thoughts on an API-First WordPress

The following is a guest post by Eduardo Bouças. We all know WordPress is a CMS, but here Eduardo thinks about using it only as an API for content. No front end at all, just URL endpoints that return JSON for use anywhere else. This doesn't detail a comprehensive solution to doing this, it's food for thought with some example code to get you going on a custom solution. If you want to get started developing on a system like this right away, WP REST API is the most robust project with the most momentum.

(more…)

Where Style Guides Fit Into Process

Brad Frost was showing me some slides from one of his talks recently. He had some graphics that demonstrated different approaches to where a style guide can fit into a team's process. As you might imagine, it's a matter of just having one or not that will determine its effectiveness.

I thought I would attempt to explain my own thoughts on these approaches based on my own experiences.

(more…)

HTML vs Body in CSS

The difference between <html></html> and <body></body> is easy to overlook. It seems to be one of those things that falls into the category of trivial. Admittedly, I have a bad habit of applying all global styles to <body></body> and, when that falls short, I move to <html></html> without thinking about it.

There are differences, however, and it's a good idea to be aware of them regardless of whether we're CSS veterans or rookies. We'll go over those in this post and consider some practical applications where styling one over the other might make sense.

(more…)

Sponsor: Mack Weldon

Guys. (Literally guys this time, sorry gals.)

I don't particularly like clothes shopping. So I don't. 95% of the clothes I own I buy online. But I also like nicely made clothes. It's not a splurge. They last longer, are more comfortable, and end up being a more economical buy.

That's why I'm glad there are companies like Mack Weldon that make high quality clothes that used to suck to shop for: underwear, undershirts, and socks. This is what they have to say specifically about their underwear:

  • We thought underwear could be better, so we made it by combining old school quality with new technology.
  • We spent 10,000 hours creating better underwear, starting with our own new fabric we call 18 Hour Jersey. The fabric sits for 18 hours before it's cut, giving it time to naturally breathe and acclimate.
  • Features like a no-roll waistband, stay-put legs and mesh cools zones make these very comfortable even after a full day's wear.

They want you to be comfortable in great underwear, so if you don't like your first pair, they'll send a different size or give you a refund. No need to send anything back.

Cut and Copy (from JavaScript)

Matt Gaunt shares that IE 10 and bleeding edge Chrome and Opera how support document.execCommand('copy'); and friends, which can make for some mighty convenience UX opportunities.

Using Chrome DevTools to Debug JavaScript in Any Browser with Ghostlab 2

The following a guest post by Andi Dysart and Matthias Christen of Ghostlab. I was pretty impressed when I heard that the newly-released Ghostlab 2 could do this. I think a lot of us developers use Chrome because the DevTools are so good, and it sure would be able to use them in other browsers, even on mobile devices. And why not? Chrome DevTools are a part of Blink, which is open source, right? We just needed a tool to make it happen.

(more…)

More Control over Text Decoration

Marie Mosley just finished up a revamping of the text-decoration property (and friends) in the Almanac. You're probably aware of this property. For instance, most default browser styles include underlined links by way of text-decoration: underline; - which you can remove with text-decoration: none;.

But you may not be aware that there is more you can do with this property, as well as various sub-properties offering more fine-grained control.

(more…)

CSS-Tricks Chronicle XXII

We put up a proper Team page. CSS-Tricks isn't just me, but a whole team of part-time staff that keep this ship sailing. That includes writers. We've always had guest posts, but now, for the first time, you'll be seeing articles not written by me that also aren't "guest" posts, because they work here! Example. Notice it doesn't have an introduction written by me like a guest post would. We'll get proper author archives up soon.

(more…)

Be Careful with will-change

The concept behind the will-change property is to stop using hacks like transform: translateZ(0) to tell browsers where to optimize and standardize it. The typical, understandable gripe is that this complicates CSS. Shouldn't browsers be smart enough to do these optimizations, rather than leaving it up to us authors? To which browsers say: it's near impossible to heuristically determine these things. Much like the sizes property in responsive images - just telling the browser allows it to act on that information much sooner. Browsers also say, it's not CSS getting more complicated, it's pages. Another gripe is that the suggested use of applying and removing will-change with JavaScript as needed is asking too much.

All that warm-up to link to Thierry Koblentz's article in which he warns that will-change can create new stacking contexts, which can be unexpected and create cross-browser differences.

Starting a Refactor with CSS Dig

The following is a guest post by Tom Genoni. Tom built an open source Chrome Extension for analyzing CSS. I'll let him introduce it.

It's a new web project. You're starting from scratch. The front end is going to be clean and orderly. You've set your defaults. Your CSS files are organized. You've got a system! This time will be different. What could possibly go wrong?

(more…)

Be experienced, not cynical.

Jamison Dance:

If you don't share experience with others, your effectiveness will never scale beyond your own efforts. If you impart your battle scars on others without considering the circumstances in which they were inflicted, people who believe you will miss out on awesome things. The challenge of the experienced developer is to pass on wisdom without passing on dogma, but most developers think their personal experience should be enshrined as a best practice.

Accessibility Wins

Marcy Sutton's new site "showcasing accessible user interfaces".

I don't know about you, but I sure like the idea of celebrating the good to balance out all the shaming of the bad.

BEM 101

The following is a collaborative post by guest Joe Richardson, Robin Rendle, and a bunch of the CSS-Tricks staff. Joe wanted to do a post about BEM, which we loved, and just about everybody around here had thoughts and opinions about BEM, so we figured we'd all get together on it and do it together.

The Block, Element, Modifier methodology (commonly referred to as BEM) is a popular naming convention for classes in HTML and CSS. Developed by the team at Yandex, its goal is to help developers better understand the relationship between the HTML and CSS in a given project.

(more…)

Browser representatives on CSS [selector] performance

My anecdotal evidence regarding CSS selector performance is: I've never once bothered with optimizing for it, and typically outright ignore traditional "advice" around it, and it's never been a problem.

Ben Frain looks around at what browser people say about it and:

At this point I'm happily re-concluding that CSS selectors are rarely a problem with static pages. Plus, attempting to second guess which selector will perform well is probably futile.

If you're doing something extraordinarily DOM-heavy, I think you know that and can worry about it then.

Loading CSS without blocking render

Typically you do want CSS to block rendering. Pages would load in a very awkward manner if you saw the page load with no CSS first, then shift around as the CSS is parsed and applied to the page.

But there are some situations where you want to defer loading of CSS - for instance a stylesheet of custom fonts you don't mind downloading late. Or even your main stylesheet if you're doing critical CSS.

Keith Clark presents a really simple way to do this in this article (no dependencies). Scott Jehl chimed in saying onload has spotty support though. His little async CSS loader is likely the best way to go for the best possible browser support.

Another way to defer loading of CSS is just to put it at the bottom of the document, like we often do with scripts. But bear in mind the advantage to doing it in the head is that the download gets triggered right away so it's ultimately a bit faster. We put scripts in the footer because it's not only the downloading of the script that can be blocking, but the execution as well (doubly whammy). I'm not sure if CSS has blocking execution (if you can call it that), but I don't think so (?).

FOUT, FOIT, FOFT

Remember FOUT? When using a custom font via @font-face, browsers used to display a fallback font in the font stack until the custom one loaded. This created a "Flash of Unstyled Text" — which was unsettling and could cause layout shifts. We worked on techniques for fighting it, for instance, making the text invisible until the font was ready.

A number of years ago, browsers started to shift their handling of this. They started to detect if text was set in a custom font that hasn't loaded yet, and made it invisible until the font did load (or X seconds had passed). That's FOIT: "Flash of Invisible Text". Should a font asset fail or take a long time, those X seconds are too long for people rightfully concerned about render time performance. At worst, this behavior can lead to permanently invisible content.

These days we're trying to fight against FOIT in various ways. In Faster Font Loading with Font Events, Jonathan Suh suggests using a library to detect if a custom font has loaded, and only then change a class name on the document to set the text in that font. This makes the behavior like FOUT - speeding up readable content at the cost of somewhat jarring visual changes.

Zach Leatherman has been writing a lot about this too. In Better @font-face with Font Load Events he also suggests waiting for the font to be loaded before setting a class to set the type. He also goes into what it takes to trigger a font download (it's not as simple as a @font-face declaration). Scott Jehl corroborates this in Font Loading Revisited with Font Events, including a bit about cookies and caching.

Zach's latest trick involved FOFT: "Flash of Faux Text". The idea here is only waiting for the Roman variant of the custom font to load, and setting text in that right away. You force the browser to create "faux bold" and "faux italic" where needed, which are replaced by the real versions as soon as those are downloaded.

Vitaly Friedman wrote about their approach on Smashing Magazine where they actually use localStorage to cache the font. It ends up being like FOUT on the first page load and (a fast) FOIT on subsequent loads.

I just think it's interesting how we flip around on this stuff every so often. The browser behaves one way and we trick it into behaving another way. It changes to that way, and we trick it into behaving the old way.

WordPress Functionality Plugins

The following is a guest post by Jason Witt. I've known for quite a while that I should port a lot of the stuff from my `functions.php` in my WordPress theme into a functionality plugin. But you know, hours in the day and all that. I recently had Jason work on this project for me, and he did a bang up job. If you have no idea what I'm talking about, read on.

Adding new functionality to a WordPress site can be as easy as searching for a plugin in the WordPress Plugin Repository and installing that plugin. But there is some custom functionality you might need that is either too basic or too customized for there to be a plugin for it. That's where the `functions.php` file comes in. It's essentially a functionality dumping grounds for a theme.

But some of the code we tend to put there would be better served elsewhere.

(more…)

Server Side Mustard Cut

The term "mustard cutting" in web design comes from developers at the BBC who wanted to serve different experiences of their site to different browsers on different devices. They were specifically trying to avoid User Agent sniffing:

But these days, with such a long tail of user agents now accessing the site, this becomes a fruitless exercise.

Instead, they used feature detection. Modernizr is the classic (awesome) example of that, but ala carte feature tests can be quite small and simple all by themselves. This is the logic the BBC used to determine if a browser cut the mustard or not:

if('querySelector' in document
     && 'localStorage' in window
     && 'addEventListener' in window) {
     // bootstrap the javascript application
     }

If that logic failed, the website still loads what they called a core experience. If that logic passed, additional resources would load for an enhanced experience.

Pretty cool.

Loading additional CSS and JavaScript is fairly easy

There are various ways to do it, typically involving an XHR for the resource. Filament Group has some very tiny, focused scripts just for this: loadCSS and loadJS.

Loading a bit of extra HTML via XHR is similarly easy. But...

It's too hard to load an entirely different document client-side

Say you don't need just a bit of extra CSS, scripts, or a bit of HTML. What you want is an entirely different document.

Your "core experience" and "enhanced experience" are entirely different sets of HTML, CSS, and JavaScript. Trying to do this client-side would mean trying to load a super bare-bones document, then trying to essentially re-create how the browser parser works. First you mustard-cut, then XHR for the right set of HTML you need, then either drop it into the DOM, or perhaps wait until you've XHR'd for the CSS so you don't get a flash of unstyled document. Then XHR for all the scripts, and make sure that you execute them in order (tricky).

Hard to pull off.

Allow the server to serve the correct document based on mustard-cutting information

If the server knew the results of your mustard-cut, you could avoid all that trouble and serve the correct document right off the bat.

That's the whole point of client-side mustard-cutting: it can only be done on the client. But... you could save that data to a cookie, and cookies can be read by the server.

It you had a cookie you could count on, you could do something like this in the routing of your site:

<?php
  // This is just a fake routing/controller kinda setup.
  if (isset($_COOKIE["mustard"])) {
    // Enhanced experience
    if ($_COOKIE["mustard"] == true) {
      include_once("enhanced.php");
    // Core experience
    } else {
      include_once("core.php");
    }
  // No cookie = core experience
  } else {
    include_once("core.php");
  }
?>

What happens on the first page view though?

That's the tricky part here. That cookie won't exist on the first page view. You could just let subsequent pages serve the correct experience, but that's not likely to be acceptable.

Here comes the most controversial part: if you don't have the cookie but can tell the browser supports them and they are enabled, you refresh the page.

Refresh the page?! Are you kidding?

Totally reasonable questions: How can a refresh possibly be a good user experience? Aren't refreshes slow? Couldn't you get caught in a refresh loop?

I think all of these things can be addressed.

At the very top of the document, if that cookie is not there and the browser does support cookies:

  1. Mustard-cut and save the data to a cookie with JavaScript
  2. If the mustard-cut data tells you you should be loading a different document: halt the page from loading/doing anything else (window.stop();) and refresh (location.reload(true);).

Upon refresh, the cookie will be there for the server.

It all happens so fast when it's the very first thing a document does that I find it barely noticeable. This is what we're doing for the editor page on CodePen, see:

Fresh page load on a new incognito window (no cookies saved). The desktop view is actually the default, but the refresh happens and the mobile view loads because of a mustard-cut.

The trick to avoiding a refresh loop is to only execute that part of the JavaScript if you're sure cookies are supported and enabled.

The mustard-cutting script

Here's a mustard-cut that only tests the screen width. Bear in mind a mustard-cut could be anything you want it to be that you can test client-side.

(function() {

  // If the browser supports cookies and they are enabled
  if (navigator.cookieEnabled) {

    // Set the cookie for 3 days
    var date = new Date();
    date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();

    // This is where we're setting the mustard cutting information.
    // In this case we're just setting screen width, but it could
    // be anything. Think http://modernizr.com/
    document.cookie = "screen-width=" + window.outerWidth + expires + "; path=/";

    /*
      Only refresh if the WRONG template loads.

      Since we're defaulting to a small screen,
      and we know if this script is running the
      cookie wasn't present on this page load,
      we should refresh if the screen is wider
      than 700.

      This needs to be kept in sync with the server
      side distinction
    */
    if (window.outerWidth > 700) {

      // Halt the browser from loading/doing anything else.
      window.stop();

      // Reload the page, because the cookie will now be
      // set and the server can use it.
      location.reload(true);

    }

  }

}());

In fact, we don't have to load that script at all if the cookie is already there, since if it is, we know the correct page has loaded already.

<?php
    // Run this script as high up the page as you can,
    // but only if the cookie isn't already present.
    if (isset($_COOKIE["screen-width"]) == 0) { ?>
      <script src="mobile-mustard.js"></script>
<?php } ?>

Possible Scenarios

  • The normal first time visitor: No cookie is present. Mustard-cut script will run and refresh the page quickly. They will get correct document based on cut.
  • The repeat visitor: Cookie is already present. They will get correct document based on cut.
  • Visitor with incorrect cookie: Perhaps they have a desktop browser but it was very narrow when the page loaded the first time, but they have since widened it. We can detect that with a CSS @media query and offer a link to correct the problem (see demo).
  • Visitor with cookies off: We serve our choice of documents. Could potentially be wrong. Serve the best likely case based on data.
  • Visitor in which JavaScript doesn't run: We serve our choice of documents. Could potentially be wrong. Serve the best likely case based on data.

Possible Problems

For the record, I'm not saying this is the best possible solution to this problem. In fact, if you're in a situation where you can do everything purely client-side, that's probably better.

Here's some potential problems with this solution:

  • Perhaps the reload is slower than I think it is. I didn't do any testing of super old / super slow devices like I probably should have.
  • HTML caching could be a problem. I experienced this first hand when building the demo on a site that was using that method. The server serves a cached document, which then is determined to be the incorrect one and refreshed, causing the dreaded refresh loop. Solution: don't HTML cache this page, or redirect to subdomains based on the cut.
  • Security settings that prevent server-side access to cookies created by JavaScript. If you can't control that, that would be a problem.

I do use this technique in production though and haven't had an issue in a lot of months, so I'm pretty happy with it.

Demo and Repo

Here's a demo and the code is up on GitHub if you spot any fouls.

Also, I thought client hints was supposed to be the savior here, but I'm just not sure anymore where it fits into this situation.

Numeric Inputs – A Comparison of Browser Defaults

The spec, purposefully, stops short of telling implementations (browsers) how to handle UI. In this article we're looking specifically at <input type="number"/>, and you might be surprised to learn that the spec specifically says:

This specification does not define what user interface user agents are to use.

It goes on to explain that different languages, cultures, and regions might have good reason to handle numeric inputs differently. So browsers are on their own here, and perhaps this time unsurprisingly, there are quite a few different approaches to the UI. Let's take a look.

(more…)

Introduction to WordPress Front End Security: Escaping the Things

If you're a WordPress developer that writes HTML/CSS/JS (which is 100% of theme developers and 99% of plugin developers), you need to know the basics of front end security for WordPress. WordPress gives you all the tools you need to make your theme or plugin secure. You just need to know how and when to use each tool.

For example, one huge responsibility you have as a front-end developer is to prevent unescaped content from being printed to the page.

(more…)

Textures.js

SVG patterns for Data Visualization by Riccardo Scalco.

This is like all my favorite web things smashed together. Beautiful design, SVG, accessibility, programmatic control with JavaScript, and open source. #swoon

Sponsor: All Courses on Skillfeed Free for a Month

For a limited time, Skillfeed is offering access to all courses and tutorials for free! Web designers and other creative professionals can pick up career-building skills in web and graphic design, CSS, Adobe software, and more, from anywhere, at anytime. To celebrate its launch, Skillfeed is offering 30 days of free access to hundreds of online courses. Take your web design skills to the next level today. Don't miss out!

Probably Use initial-scale=1

If you're doing responsive design, you're using viewport <meta /> tags. These tell the browser what width it should render the viewport at. If you don't use this tag, it will render at the device's default, which almost certainly isn't what you want. But even if you are using viewport <meta />, there are subtle differences in the value you put in it.

I just wanna focus on one little difference here.

(more…)

Left Half and Right Half Layout – Many Different Ways

A whole bunch of years ago, we posted on this idea here on CSS-Tricks. We figured it was about time to update that and do the subject justice.

Imagine a scenario where you need to split a layout in half. Content on the left and content on the right. Basically two equal height columns are needed inside of a container. Each side takes up exactly half of the container, creating a distinct break between one. Like many things in CSS, there are a number of ways to go about this and we're going to go over many of them right now!

(more…)

Strategies for Staying on Top of Web Performance

Step one is caring about the performance of your websites. Step two is doing things to make it better. Step three is staying on top of performance for the long haul.

That means not just poking at trying to improve your web performance a few times a year, but making it a part of your active development and trying to prevent regressions. Certainly something that gets harder the more actively developed your site is.

(more…)

Sponsored: Creative Market’s March Big Bundle

Fill up your toolbox with a ton of design resources from Creative Market! 77 really nice fonts, graphics, vectors, brushes, stamps, patterns, themes, branding kits, and more that all reflect current trends and tastes in visual design. Purchased individually, everything would cost over $1,200 - on sale this week only for $39.

Get it now →

New Poll: You get this email…

Maybe you know the kind. It's from someone you've never met, but it sounds like good news. They have an idea for new web thing. They know what you do, and they want your help. In fact, they want to cut you in on it, perhaps co-found this company. Control over the parts that matter to you. It's a decent idea. Not mind-blowing, but lots of ideas seem kind mediocre at first right? It's what you do with them, you think.

(more…)

What Does My Site Cost?

With the average website size closing in on 2 MB (!), Tim Kadlec's new site forces us to think how much money it costs to load a single website when you're paying for data on a mobile connection. In Germany, that's a dang U.S. quarter for one site.

Em-based media queries are based on…

(drumroll please)

Stephanie Rewis (off a lead from Susan Robertson):

the em base in media queries comes from the user's setting (which is the 16px browser default if not changed by the user).

Intuitively, it seems like changing the font-size at the :root / html level would change what 1em is and thus change where breakpoints hit, but it doesn't.

Em-based media queries got very popular after Lyza Gardner detailed how breakpoints didn't hit as you'd expect with browser zooming. That's not the case anymore, and I still that fact quoted a lot. So just be aware that you don't have to force yourself to use em-based media queries if you don't otherwise need to or prefer to — and if you do use them, assuming 1em = 16px is the best you can do.

Poll Wrapup: The Number of People Touching CSS

The last poll around here was:

How many people touch the CSS in your current main project?

Defined as:

  • Actually author and edit it.
  • Or, are an active consumer of it. You/they write HTML and use the CSS available thus have a vested interest in the actual CSS, not just the outcome.

My desire with this poll was to get a sense of how shared CSS is. Is CSS the kind of code that is generally in and out of a lot of different peoples hands and heads? Or is it more intimate than that?

(more…)

Using the HTML5 History API

The HTML5 History API gives developers the ability to modify a website's URL without a full page refresh. This is particularly useful for loading portions of a page with JavaScript, such that the content is significantly different and warrants a new URL.

Here's an example. Let's say a person navigates from the homepage of a site to the Help page. We're loading the content of that Help page with Ajax. That user then heads off to the Products page which we again load and swap out content with Ajax. Then they want to share the URL. With the History API, we could have been changing the URL of the page right along with the user as they navigate, so the URL they see (and thus share or save) is relevant and correct.

(more…)

Sponsored: Win a Full Scholarship to Attend Launch Academy

For two years now, Launch Academy has given the gift of loving what you do to each of their 250+ graduates. To celebrate, they want to provide someone with that same gift, for free. Show them your love for code, and you could win a full scholarship (worth $12,500) to attend Launch Academy this summer! You can become a software developer at a technology company in 10 weeks at no cost to you.

Simply submit a solution to the coding challenge with your application. The best submission will receive a full scholarship. Just by submitting an entry you are eligible to win one of 10 free Macbook Airs.

The contest ends March 20th, so get started today. Good luck and have some fun with it!

I like how percentage background-position works

I learned something the other day when we were fleshing out the background properties in the Almanac. It's such an intuitive thing, that I guess I just never stopped to think about it before.

By default, background-position is 0 0, the top left corner. Now imagine you set it to 50% 0. That background image is now center top. It figures out the size of that image, and positions the center of it at the center of the element.

(more…)

Quantity Queries for CSS

Heydon Pickering with some clever CSS selectors like:

li:nth-last-child(n+6),
li:nth-last-child(n+6) ~ li {
  /* Selects all list items if there are 6 or more */
}

Similar to Matt Mastracci's article where he focuses on styles for groups of specific numbers.

Using AngularJS for Data Visualisations

The following is a guest post by Nick Moreton. I gotta say I find this idea rather intriguing. I know that I love working in HTML, SVG, and CSS, so when Nick shares that we can use that for structure and use the data directly to style a chart, that appeals to me. And then to know that, because you're using Angular, the chart can automatically change when the data changes... that's just dang cool.

(more…)

Dropdown Menus with More Forgiving Mouse Movement Paths

This is a fairly old UX concept that I haven't heard talked about in a while, but is still relevant in the case of multi-level dropdown menus. A fine-grained pointer like a mouse sometimes has to travel through pretty narrow corridors to accurately get where it needs to in a dropdown menu. It's easy to screw up (have the mouse pointer leave the path) and be penalized by having it close up on you. Perhaps we can make that less frustrating.

(more…)

Accidental CSS Resets

Any time you use a shorthand property in CSS, you set all the values for all the properties it deals with. It's not a bug, it's just how CSS works. I've seen it confuse people plenty of times. Let's shine a light on the issue to hopefully make it more understood.

(more…)

Thoughts on the Advertising Ecosystem

There are lots of business on the web. One type of those is a website that sells products or services. Those websites employ people who work on the site, incur server costs, material costs, etc. The products and services they provide are useful to people, and they pay for them. Business. Cool.

Those websites need customers. They need people to come to those sites. There are all sorts of ways to do that. Word of mouth. SEO. Wear a costume and wave a sign at traffic. Some more effective than others. The most effective, generally is to do marketing and, as a subset of that, do advertising. Web advertising, in particular, as potential customers are just a click away.

Where do you do that advertising? Enter another type of business on the web: the publication.

(more…)

CSS-Tricks Chronicle XXI

As I write I'm half way through my month-long stay at Hilton Head Health. I like coming here to keep my weight in check. I hope to break some personal records while I'm here this time. It's also been a good way to escape some of the Wisconsin winter. It has been mild up until I left, but it sounds like February has been pretty rough so far.

(more…)

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