CSS-Tricks

Subscribe to CSS-Tricks feed
Tips, Tricks, and Techniques on using Cascading Style Sheets.
Updated: 4 hours 20 min ago

Slate’s URLs Are Getting a Makeover

Fri, 12/08/2017 - 00:37

Greg Lavallee writes about a project currently underway at Slate, where they’ve defined a new goal for themselves:

Our goal is speed: Readers should be able to get to what they want quickly, writers should be able to swiftly publish their posts, and developers should be able to code with speed.

They’ve already started shipping a lot of neat improvements to the website but the part that really interests me is where they focus on redefining their URLs:

As a web developer and product dabbler, I love URLs. URLs say a tremendous amount about an application’s structure, and their predictability is a testament to the elegance of the systems behind them. A good URL should let you play with it and find delightful new things as you do.

Each little piece of our new URL took a significant amount of planning and effort by the Slate tech team.

The key takeaway? URLs can improve user experience. In the case of Slate, their URL structure contained redundant subdirectory paths, unnecessary bits, and inverted information. The result is something that reads more like a true hierarchy and informs the reader that there may be more goodies to discover earlier in the path.

Direct Link to ArticlePermalink

Slate’s URLs Are Getting a Makeover is a post from CSS-Tricks

On Building Features

Thu, 12/07/2017 - 17:18

We've released a couple of features recently at CodePen that I played a role in. It got me thinking a little bit about the process of that. It's always unique, and for a lot of reasons. Let's explore that.

What was the spark?

Features start with ideas.

Was it a big bright spark that happened all the sudden? Was it a tiny spark that happened a long time ago, but has slowly grown bright?

Documenting ideas can help a lot. We talked about that on CodePen Radio recently. If you actually write down ideas (both your own and as requested by users), it can clarify and contextualize them.

Documenting all ideas in Notion

There is tooling (e.g. Uservoice) which is specifically for user feedback guiding feature development as well.

Personally, I prefer a mix of internal product vision with measured customer requests, staying light on the public roadmap.

The addition of design assets on CodePen, one of the recent features I worked on, was more of a slowly-intenifying spark than a hot-and-fast one. It came from years of aggregated user requests. CodePen should have a color picker. That'd be neat, we would think. It should be easier to use custom fonts. Yeah... we also jump around copying code from Google Fonts awful regularly.

Then we get an email from Unsplash that was essentially hey, ya know, we have an API. Hmmmm. You sure do! The spark then was gosh all these things feel really related. They are all things that help you with design. Design assets, as it were.

Perhaps we could say this is a good recipe to kick off a new feature: It seems like a good idea. Your instinct is to do it. You want it yourself. You have enough research that your users want it too.

While you're in there...

The spark has been lit. It feels like a good idea and should be done now. Now what?

When you're working on a new feature for an existing project, you can't help but consider where it fit's into the applications UI and UX. Perhaps it's just the designer in me, but design-led feature development really seems like the way to go. First, decide exactly what it's going to do, be like to use, and look like, then build around that.

I'm always the buzzkill when it comes to non UI and UX features and improvements. I try to turn Let's switch to Postgres into Let's find a way, if we really gotta switch to Postgres, to give something to the users while we do it. But I digress.

I'd wager most new features aren't let's add an entirely new area to the site. Most site work is adding/removing/refining smaller bits to what is already there.

In the case of the new design assets feature we were building, it was clear we wanted to add it inside our code editor, as that's where you would need them. Our tendency is generally let's make a new modal! I'm not anti-modal in a situation like this. Click a button, switch mental contexts for a moment to find a design asset, copy what you need, then close it and use it. Plus we already use modals quite a bit within the editor, so there is a built-up affordance to this kind of interaction.

But a new modal? Maybe. Some things warrant entirely new UI. The minute we start considering new UI though, I always consider that a woah there cowboy moment. Not because new UI is difficult, in fact, because it's too easy. I'd much rather refine what we already have, when possible. That's where this feature took us.

We already have an assets feature, which allows people to upload files that are, quite often, design assets! Why not combine those two worlds? And this is the while you're in there... moment. Our existing Assets modal needed some love anyway. There is a similar backlog of ideas for improving that.

So this became an opportunity to not just create a new feature, but clean up an existing feature. We fleshed out the feature set for existing asset uploads as well, offering easier UX, like click-to-copy buttons and action buttons that allow you to add the URLs as external resources, or pop them open in our asset editor to make changes.

Cleaing up goes for UI design work, front-end code, and back-end code as well. Certainly the CSS, as readers of this site know! Features are a great excuse for spring cleaning.

Who can work on it?

This is a huge question to answer when it comes to new feature development. Even small teams (like I'm on) are subdivided into smaller ones on a per-feature basis.

To arrive at the answer for a new feature, it can be hugely beneficial to one-sheet that sucker. A one-sheet is a document that you construct at the beginning of building a new thing where you scope out what is required.

It forces you to not think narrowly about what you are about to do, but broadly. That way you avoid situations where you're like I'll just add this little checkbox over here ... 7 months later, 2,427 files touched ... done!

A one-sheet document might be like this:

  • Overview. Explain what you're building and why.
  • Alternate solutions. Have you thought of multiple ways to approach this?
  • Front-end overview. Including design, accessibility, and performance.
  • Back-end overview.
  • Data Considerations. Does this touch the database?
  • API and services considerations.
  • Customer support considerations. Is it likely this will cause more or less support?
  • Monitoring, logging, and analytics considerations.
  • Security considerations.
  • Testing considerations.
  • Community safety considerations.
  • Cost considerations.

If you've gone through that whole list in earnest and written up everything, you'll be in much better shape. You'll know exactly what this new feature will take and be closer to estimating a timeline.

Crucially, you'll know who you need to work on it.

This passage, from Fabricio Teixeira, rings true:

Designers have to understand how digital products work beyond the surface layer, and how even the tiniest design decision can create a ripple effect on many other places.

You have to bring other disciplines to the table when you start talking about a “minor design change” in your product. There’s a good chance “minor design changes” don’t really exist.

When it came to our design assets mini feature, one of the major reasons we were able to jump on it was because, assuming we scoped what it was going to do appropriately (see next section), 90%+ of the work could be done by a single front-end developer/designer. Of anyone, I had the most open schedule, so I was able to take it on.

Some feature, perhaps most features, require more interdiciplinary teams. Huge features, on our small team, usually take just about everybody.

Version One vs. The Future

It's highly likely you'll have to scope down your ideas to something manageable. It's so tempting to go big with ideas, but the bigger you go, the slower you go. I'm sure we've all been in situations where even small features take three times as long as you expected them to.

I try to be the guy jamming stuff out the door, at least when I'm a place where I know refininements and polish aren't pipe dreams. I tend to find more trouble with scope creep and delays than things going out too quickly.

When it came to our design assets feature, as I mentioned, I wanted to scope it to an almost front-end-only project at first, so that it didn't require a bunch of us to work on it. That was balanced with the fact that it I was sure we could make it pretty useful without needing a ton of backend work. I wouldn't hamstring a feature just for people availability reasons, but sometimes the stars align that way.

The color-picker part of the design assets modal is a good example of that. Right away we considered that someone might want to save their own favorite colors as a palette. Perhaps on a per-Pen basis or global to their account. I think that's a neat idea too, but that requires some user database work to prepare us for that. It seems like a quite small thing, but we would definitely take our time with something like that to make sure the database changes were abstract enough that we werent just slapping on a "favorite colors" column, but a system that would scale appropriately.

So a simple color picker can be "v1"! No problem! Get that thing out the door. See how people use it. See what they ask for. Then refine it and add to it as needed.

To be perfectly honest, there hasn't been an awful lot of feedback on it. That's usually one for the win column. People vocally loving it is certainly better, but that's rare. When products work and do what people want, the usually just silently and contentfully go about their business. But if you get in their way, at least at a certain scale, they'll tell you.

Perhaps one day we'll revisit the design assets area and do a v2! Saved favorites. More image search providers. More search in general. Better memory for what you've used before and showing you those things faster. That kind of refining might require a different team. It's also just as satisfying of a project as the v1, if not more so.

Here's a better look at what v1 turned out to be:

Another example... CodePen's new External Assets

Speaking of refining a feature! Let's map this stuff onto another feature we recently worked on at CodePen. We just revamped how our External Assets area works. This is what it's like now:

It's somewhat unlikely most people have a strong memory of what it was like before. This isn't that different. The big UI difference is that big search box. Before, the inputs were the search fields, typeahead style. We're still using typeahead, but have moved it to the search box, which I think is a stronger affordance.

Moving where typeahead takes place is a minor change indeed, but we had lots of evidence that people had no idea we even offered it. Using the visual search affordance completely fixes that.

Another significant UX improvement comes in the form of those remembered resources. Whenever you choose a resource, it remembers you did, and gives you a little button for adding it again. Hey! That's a lot like favoriting design assets, isn't it?! Good thing we didn't make that "favorite colors" database column because already we're seeing places a more abstract system would be useful.

In this case, we decided to save those favorites in localStorage. Now we get to experiment with a UI in a way that handles favorites, but still not need to touch the database quite yet. The advantage of moving it to the database is that favorites of any kind could follow a user across browsers and sessions and stuff without worry of losing them. There is always a v3!

There was also some behind-the-scenes updates here that, internally, we're just as excited about. That typeahead feature? it searches like tens or hundreds of thousands of resources. That's a lot of data. Before this, we handled it by not downloading that data until you clicked into a typeahead field. But then we did download it. A huge chunk of JSON we stored on our own servers. A huge chunk of JSON that went out of data regularly, and required us to update all the time. We had a system for updating it, but it still required work. The new system uses the CDNjs API directly, meaning that no huge download ever needs to take place and the resources are always up to date. Well, as up to date as CDNjs is, anyway.

Speaking of a v3, we already have loads of ideas for that. Speed is a slight concern. How can we speed up the search? How can we scope those results by popularity? How can we loosen up and guess better what resource you are searching for? Probably most significantly, how can we open this up to resources on npm? We're hoping to address all of this stuff. But fortunately, none of it held up getting a better thing out the door now.

Wrapping Up

A bit of a ramble eh?

Definitely some incomplete thoughts here, but feature development has been on the ol' brain a lot lately and I wanted to get something down. So many of us developers live in this cycle our entire career. A lot of us have significant say in what we build and how we build it. There is an incredible amount to think about related to all this, and arguably no obvious set of best practices. It's too big, too nebulous. You can't hold it in your hand and say this is how we do feature development. But you can think real hard about it, have some principles that work for you, and try to do the best you can.

On Building Features is a post from CSS-Tricks

​HelloSign API: Your development time matters

Thu, 12/07/2017 - 16:53

(This is a sponsored post.)

We know that no API can write your code for you, but ours comes close. We've placed great importance on making sure our API is the most developer-friendly API available — prioritizing clean documentation, an industry-first API dashboard for easy tracking and debugging, and trained API support engineers to personally assist with your integration.  Meaning, you won't find an eSignature product with an easier or faster path to implementation.  It's 2x faster than other eSignature APIs.  

If you're a business looking for a way to integrate eSignatures into your website or app, test drive HelloSign API for free today.

Direct Link to ArticlePermalink

​HelloSign API: Your development time matters is a post from CSS-Tricks

Making your web app work offline, Part 2: The Implementation

Thu, 12/07/2017 - 14:33

This two-part series is a gentle, high-level introduction to offline web development. In Part 1 we got a basic service worker running, which caches our application resources. Now let's extend it to support offline.

Article Series:
  1. The Setup
  2. The Implementation (you are here!)
Making an `offline.htm` file

Next, lets add some code to detect when the application is offline, and if so, redirect our users to a (cached) `offline.htm`.

But wait, if the service worker file is generated automatically, how do we go about adding in our own code, manually? Well, we can add an entry for importScripts, which tells our service worker to import the scripts we specify. It does this through the service worker’s native importScripts function, which is well-named. And we’ll also add our `offline.htm` file to our statically cached list of files. The new files are highlighted below:

new SWPrecacheWebpackPlugin({ mergeStaticsConfig: true, filename: "service-worker.js", importScripts: ["../sw-manual.js"], staticFileGlobs: [ //... "offline.htm" ], // the rest of the config is unchanged })

Now, let’s go in our `sw-manual.js` file, and add code to load the cached `offline.htm` file when the user is offline.

toolbox.router.get(/books$/, handleMain); toolbox.router.get(/subjects$/, handleMain); toolbox.router.get(/localhost:3000\/$/, handleMain); toolbox.router.get(/mylibrary.io$/, handleMain); function handleMain(request) { return fetch(request).catch(() => { return caches.match("react-redux/offline.htm", { ignoreSearch: true }); }); }

We’ll use the toolbox.router object we saw before to catch all our top-level routes, and if the main page doesn’t load from the network, send back the (hopefully cached) `offline.htm` file.

This is one of the few times in this post you’ll see promises being used directly, instead of with the async syntax, mainly because in this case it’s actually easier to just tack on a .catch(), rather than set up a try{} catch{} block.

The `offline.htm` file will be pretty basic, just some HTML that reads cached books from IndexedDB, and displays them in a rudimentary table. But before showing that, let’s walk through how to actually use IndexedDB (if you want to just see it now, it’s here)

Hello World, IndexedDB

IndexedDB is an in-browser database. It’s ideal for enabling offline functionality since it can be accessed without network connectivity, but it’s by no means limited to that.

The API pre-dates Promises, so it’s callback based. We'll go through everything with the native API, but in practice, you’ll likely want to wrap and simplify it, either with your own helper methods which wrap the functionality with Promises, or with a third-party utility.

Let me repeat: the API for IndexedDB is awful. Here’s Jake Archibald saying he wouldn’t even teach it directly

I always teach the underlying API rather than an abstraction, but I'd make an exception for IDB.

— Jake Archibald (@jaffathecake) December 2, 2017

We'll still go over it because I really want you to see everything as it is, but please don’t let it scare you away. There’s plenty of simplifying abstractions out there, for example dexie and idb.

Setting up our database

Let’s add code to sw-manual that subscribes to the service worker’s activate event, and checks to see if we already have an IndexedDB setup; if not, we’ll create, and then fill it with data.

First, the creating bit.

self.addEventListener("activate", () => { //1 is the version of IDB we're opening let open = indexedDB.open("books", 1); //should only be called the first time, when version 1 does not exist open.onupgradeneeded = evt => { let db = open.result; //this callback should only ever be called upon creation of our IDB, when an upgrade is needed //for version 1, but to be doubly safe, and also to demonstrade this, we'll check to see //if the stores exist if (!db.objectStoreNames.contains("books") || !db.objectStoreNames.contains("syncInfo")) { if (!db.objectStoreNames.contains("books")) { let bookStore = db.createObjectStore("books", { keyPath: "_id" }); bookStore.createIndex("imgSync", "imgSync", { unique: false }); } if (!db.objectStoreNames.contains("syncInfo")) { db.createObjectStore("syncInfo", { keyPath: "id" }); evt.target.transaction .objectStore("syncInfo") .add({ id: 1, lastImgSync: null, lastImgSyncStarted: null, lastLoadStarted: +new Date(), lastLoad: null }); } evt.target.transaction.oncomplete = fullSync; } }; });

The code’s messy and manual; as I said, you’ll likely want to add some abstractions in practice. Some of the key points: we check for the objectStores (tables) we’ll be using, and create them as needed. Note that we can even create indexes, which we can see on the books store, with the imgSync index. We also create a syncInfo store (table) which we’ll use to store information on when we last synced our data, so we don’t pester our servers too frequently, asking for updates.

When the transaction has completed, at the very bottom, we call the fullSync method, which loads all our data. Let’s see what that looks like.

Performing an initial sync

Below is the relevant portion of the syncing code, which makes repeated calls to our endpoint to load our books, page by page, adding each result to IDB along the way. Again, this is using zero abstractions, so expect a lot of bloat.

See this GitHub gist for the full code, which includes some additional error handling, and code which runs when the last page is finished.

function fullSyncPage(db, page) { let pageSize = 50; doFetch("/book/offlineSync", { page, pageSize }) .then(resp => resp.json()) .then(resp => { if (!resp.books) return; let books = resp.books; let i = 0; putNext(); function putNext() { //callback for an insertion, with indicators it hasn't had images cached yet if (i < pageSize) { let book = books[i++]; let transaction = db.transaction("books", "readwrite"); let booksStore = transaction.objectStore("books"); //extend the book with the imgSync indicated, add it, and on success, do this for the next book booksStore.add(Object.assign(book, { imgSync: 0 })).onsuccess = putNext; } else { //either load the next page, or call loadDone() } } }); }

The putNext() function is where the real work is done. This serves as the callback for each successful insertion’s success. In real life we’d hopefully have a nice method that adds each book, wrapped in a promise, so we could do a simple for of loop, and await each insertion. But this is the "vanilla" solution or at least one of them.

We modify each book before inserting it, to set the imgSync property to 0, to indicate that this book has not had its image cached, yet.

And after we’ve exhausted the last page, and there are no more results, we call loadDone(), to set some metadata indicating the last time we did a full data sync.

In real life, this would be a good time to sync all those images, but let’s instead do it on-demand by the web app itself, in order to demonstrate another feature of service workers.

Communicating between the web app, and service worker

Let’s just pretend it would be a good idea to have the books’ covers load the next time the user visits our page when the service worker is running. Let’s have our web app send a message to the service worker, and we’ll have the service worker receive it, and then sync the book covers.

From our app code, we attempt to send a message to a running service worker, instructing it to sync images.

In the web app:

if ("serviceWorker" in navigator) { try { navigator.serviceWorker.controller.postMessage({ command: "sync-images" }); } catch (er) {} }

In `sw-manual.js`:

self.addEventListener("message", evt => { if (evt.data && evt.data.command == "sync-images") { let open = indexedDB.open("books", 1); open.onsuccess = evt => { let db = open.result; if (db.objectStoreNames.contains("books")) { syncImages(db); } }; } });

In sw-manual we have code to catch that message, and call the syncImages() method. Let’s look at that, next.

function syncImages(db) { let tran = db.transaction("books"); let booksStore = tran.objectStore("books"); let idx = booksStore.index("imgSync"); let booksCursor = idx.openCursor(0); let booksToUpdate = []; //a cursor's onsuccess callback will fire for EACH item that's read from it booksCursor.onsuccess = evt => { let cursor = evt.target.result; //if (!cursor) means the cursor has been exhausted; there are no more results if (!cursor) return runIt(); let book = cursor.value; booksToUpdate.push({ _id: book._id, smallImage: book.smallImage }); //read the next item from the cursor cursor.continue(); }; async function runIt() { if (!booksToUpdate.length) return; for (let book of booksToUpdate) { try { //fetch, and cache the book's image await preCacheBookImage(book); let tran = db.transaction("books", "readwrite"); let booksStore = tran.objectStore("books"); //now save the updated book - we'll wrap the IDB callback-based opertion in //a manual promise, so we can await it await new Promise(res => { let req = booksStore.get(book._id); req.onsuccess = ({ target: { result: bookToUpdate } }) => { bookToUpdate.imgSync = 1; booksStore.put(bookToUpdate); res(); }; req.onerror = () => res(); }); } catch (er) { console.log("ERROR", er); } } } }

We’re cracking open the imageSync index from before, and reading all books that have a zero, which means they haven’t had their images sync'd yet. The booksCursor.onsuccess will be called over and over again, until there are no books left; I’m using this to put them all into an array, at which point I call the runIt() method, which runs through them, calling preCacheBookImage() for each. This method will cache the image, and if there are no unforeseen errors, update the book in IDB to indicate that imgSync is now 1.

If you’re wondering why in the world I’m going through the trouble to save all the books from the cursor into an array, before calling runIt(), rather than just walking through the results of the cursor, and caching and updating as I go, well — it turns out transactions in IndexedDB are a bit weird. They complete when you yield to the event loop unless you yield to the event loop in a method provided by the transaction. So if we leave the event loop to go do other things, like make a network request to pull down an image, then the cursor’s transaction will complete, and we’ll get an error if we try to continue reading from it later.

Manually updating the cache.

Let’s wrap this up, and look at the preCacheBookImage method which actually pulls down a cover image, and adds it to the relevant cache, (but only if it’s not there already.)

async function preCacheBookImage(book) { let smallImage = book.smallImage; if (!smallImage) return; let cachedImage = await caches.match(smallImage); if (cachedImage) return; if (/https:\/\/s3.amazonaws.com\/my-library-cover-uploads/.test(smallImage)) { let cache = await caches.open("local-images1"); let img = await fetch(smallImage, { mode: "no-cors" }); await cache.put(smallImage, img); } }

If the book has no image, we’re done. Next, we check if it’s cached already — if so, we’re done. Lastly, we inspect the URL, and figure out which cache it belongs in.

The local-images1 cache name is the same from before, which we set up in our dynamic cache. If the image in question isn’t already there, we fetch it, and add it to cache. Each cache operation returns a promise, so the async/await syntax simplifies things nicely.

Testing it out

The way it’s set up, if we clear our service worker either in dev tools, below, or by just opening a fresh incognito window...

...then the first time we view our app, all our books will get saved to IndexedDB.

When we refresh, the image sync will happen. So if we start on a page that’s already pulling down these images, we’ll see our normal service worker saving them to cache (ahem, assuming we delay the ajax call to give our Service Worker a chance to install), which is what these events are in our network tab.

Then, if we navigate elsewhere and refresh, we won’t see any network requests for those image, since our sync method is already finding everything in cache.

If we clear our service workers again, and start on this same page, which is not otherwise pulling these images down, then refresh, we’ll see the network requests to pull down, and sync these images to cache.

Then if we navigate back to the page that uses these images, we won’t see the calls to cache these images, since they’re already cached; moreover, we’ll see these images being retrieved from cache by the service worker.

Both our runtimeCaching provided by sw-toolbox, and our own manual code are working together, off of the same cache.

It works!

As promised, here’s the `offline.htm` page

<div style="padding: 15px"> <h1>Offline</h1> <table class="table table-condescend table-striped"> <thead> <tr> <th></th> <th>Title</th> <th>Author</th> </tr> </thead> <tbody id="booksTarget"> <!--insertion will happen here--> </tbody> </table> </div> let open = indexedDB.open("books"); open.onsuccess = evt => { let db = open.result; let transaction = db.transaction("books", "readonly"); let booksStore = transaction.objectStore("books"); var request = booksStore.openCursor(); let rows = ``; request.onsuccess = function(event) { var cursor = event.target.result; if(cursor) { let book = cursor.value; rows += ` <tr> <td><img src="${book.smallImage}" /></td> <td>${book.title}</td> <td>${Array.isArray(book.authors) ? book.authors.join("<br/>") : book.authors}</td> </tr>`; cursor.continue(); } else { document.getElementById("booksTarget").innerHTML = rows; } }; }

Now let’s tell Chrome to pretend to be offline, and test it out:

Cool!

Where to, from here?

We’re barely scratching the surface. Your users can update these data from multiple devices, and each one will need to keep in sync somehow. You could either periodically wipe your IDB tables and re-sync; have the user manually trigger a re-sync when they want; or you could get really ambitious and try to log all your mutations on your server, and have each service worker on each device request all changes that happened since the last time it ran, in order to sync up.

The most interesting solution here is PouchDB, which does this syncing for you; the catch is it’s designed to work with CouchDB, which you may or may not be using.

Syncing local changes

For one last piece of code, let’s consider an easier problem to solve: syncing your IndexedDB with changes that are made right this minute, by your user who’s using your web app. We can already intercept fetch requests in the service worker, so it should be easy to listen for the right mutation endpoint, run it, then then peak at the results and update IndexedDB accordingly. Let’s take a look.

toolbox.router.post(/graphql/, request => { //just run the request as is return fetch(request).then(response => { //clone it by necessity let respClone = response.clone(); //do this later - get the response back to our user NOW setTimeout(() => { respClone.json().then(resp => { //this graphQL endpoint is for lots of things - inspect the data response to see //which operation we just ran if (resp && resp.data && resp.data.updateBook && resp.data.updateBook.Book) { syncBook(resp.data.updateBook.Book); } }, 5); }); //return the response to our user NOW, before the IDB syncing return response; }); }); function syncBook(book) { let open = indexedDB.open("books", 1); open.onsuccess = evt => { let db = open.result; if (db.objectStoreNames.contains("books")) { let tran = db.transaction("books", "readwrite"); let booksStore = tran.objectStore("books"); booksStore.get(book._id).onsuccess = ({ target: { result: bookToUpdate } }) => { //update the book with the new values ["title", "authors", "isbn"].forEach(prop => (bookToUpdate[prop] = book[prop])); //and save it booksStore.put(bookToUpdate); }; } }; }

This may seem a bit more involved than you were hoping. We can only read the fetch response once, and our application thread will also need to read it, so we’ll first clone the response. Then, we’ll run a setTimeout() so we can return the original response to the web application/user as quickly as possible, and do what we need thereafter. Don’t just rely on the promise in respClone.json() to do this, since promises use microtasks. I’ll let Jake Archibald explain what exactly that means, but the short of it is that they can starve the main event loop. I’m not quite smart enough to be certain whether that applies here, so I just went with the safe approach of setTimeout.

Since I’m using GraphQL, the responses are in a predictable format, and it’s easy to see if I just performed the operation I’m interested in, and if so I can re-sync the affected data.

Further reading

Literally everything here is explained in wonderful depth in this book by Tal Ater. If you’re interested in learning more, you can’t beat that as a learning resource.

For some more immediate, quick resources, here’s an MDN article on IndexedDB, and a service workers introduction, and offline cookbook, both from Google.

Parting thoughts

Giving your user useful things to do with your web app when they don’t even have network connectivity is an amazing new ability web developers have. As you’ve seen though, it’s no easy task. Hopefully this post has given you a realistic idea of what to expect, and a decent introduction to the things you’ll need to do to accomplish this.

Article Series:
  1. The Setup
  2. The Implementation (you are here!)

Making your web app work offline, Part 2: The Implementation is a post from CSS-Tricks

Making your web app work offline, Part 1: The Setup

Wed, 12/06/2017 - 14:57

This two-part series is a gentle introduction to offline web development. Getting a web application to do something while offline is surprisingly tricky, requiring a lot of things to be in place and functioning correctly. We're going to cover all of these pieces from a high level, with working examples. This post is an overview, but there are plenty of more-detailed resources listed throughout.

Article Series:
  1. The Setup (you are here!)
  2. The Implementation (posts tomorrow, stay tuned)
Basic approach

I’ll be making heavy use of JavaScript’s async/await syntax. It’s supported in all major browsers and Node, and greatly simplifies Promise-based code. The link above explains async well, but in a nutshell they allow you to resolve a promise, and access its value directly in code with await, rather than calling .then and accessing the value in the callback, which often leads to the dreaded "rightward drift."

What are we building?

We’ll be extending an existing booklist project to sync the current user’s books to IndexedDB, and create a simplified offline page that’ll show even when the user has no network connectivity.

Starting with a service worker

The one non-negotiable thing you need for offline development is a service worker. A service worker is a background process that can, among other things, intercept network requests; redirect them; short circuit them by returning cached responses; or execute them as normal and do custom things with the response, like caching.

Basic caching

Probably the first, most basic, yet high impact thing you’ll do with a service worker is have it cache your application’s resources. Service worker and the cache it uses are extremely low-level primitives; everything is manual. In order to properly cache your resources you’ll need to fetch and add them to a cache, but then you’ll also need to track changes to these resources. You'll track when they change, remove the prior version, and fetch and update the new one.

In practice, this means your service worker code will need to be generated as part of a build step, which hashes your files, and generates a file that’s smart enough to record these changes between versions, and update caches as needed.

Abstractions to the rescue

This is extremely tedious and error-prone code that you’d likely never want to write yourself. Luckily some smart people have written abstractions to help, namely sw-precache, and sw-toolbox by the great people at Google. Note, Google has since deprecated these tools in favor of the newer Workbox. I’ve yet to move my code over since sw-* works so well, but in any event the ideas are the same, and I’m told the conversion is easy. And it’s worth mentioning that sw-precache currently has about 30,000 downloads per day, so it’s still widely used.

Hello World, sw-precache

Let’s jump right in. We’re using webpack, and as webpack goes, there’s a plugin, so let’s check that out first.

// inside your webpack config new SWPrecacheWebpackPlugin({ mergeStaticsConfig: true, filename: "service-worker.js", staticFileGlobs: [ //static resources to cache "static/bootstrap/css/bootstrap-booklist-build.css", ... ], ignoreUrlParametersMatching: /./, stripPrefixMulti: { //any paths that need adjusting "static/": "react-redux/static/", ... }, ... })

By default ALL of the bundles webpack makes will be precached. We’re also manually providing some paths to static resources I want cached in the staticFileGlobs property, and I’m adjusting some paths in stripPrefixMulti.

// inside your webpack config const getCache = ({ name, pattern, expires, maxEntries }) => ({ urlPattern: pattern, handler: "cacheFirst", options: { cache: { maxEntries: maxEntries || 500, name: name, maxAgeSeconds: expires || 60 * 60 * 24 * 365 * 2 //2 years }, successResponses: /0|[123].*/ } }); new SWPrecacheWebpackPlugin({ ... runtimeCaching: [ //pulls in sw-toolbox and caches dynamically based on a pattern getCache({ pattern: /^https:\/\/images-na.ssl-images-amazon.com/, name: "amazon-images1" }), getCache({ pattern: /book\/searchBooks/, name: "book-search", expires: 60 * 7 }), //7 minutes ... ] })

Adding the runtimeCaching section to our SWPrecacheWebpackPlugin pulls in sw-toolbox and lets us cache urls matching a certain pattern, dynamically, as needed—with getCache helping keep the boilerplate to a minimum.

Hello World, sw-toolbox

The entire service worker file that’s generated is pretty big, but let’s just look at a small piece, namely one of the dynamic caches from above:

toolbox.router.get(/^https:\/\/images-na.ssl-images-amazon.com/, toolbox.cacheFirst, { cache: { maxEntries: 500, name: "amazon-images1", maxAgeSeconds: 63072000 }, successResponses: /0|[123].*/ });

sw-toolbox has provided us with a nice, high-level router object we can use to hook into various URL requests, MVC-style. We’ll use this to setup offline shortly.

Don’t forget to register the service worker

And, of course, the existence of the service worker file that’s generated above is of no use by itself; it needs to be registered. The code looks like this, but be sure to either have it inside an onload listener, or some other place that’ll be guaranteed to run after the page has loaded.

if ("serviceWorker" in navigator) { navigator.serviceWorker.register("https://cdn.css-tricks.com/service-worker.js"); }

There we have it! We got a basic service worker running, which caches our application resources. Tune in tomorrow when we extend it to support offline.

Article Series:
  1. The Setup (you are here!)
  2. The Implementation (posts tomorrow, stay tuned)

Making your web app work offline, Part 1: The Setup is a post from CSS-Tricks

Animating Border

Tue, 12/05/2017 - 14:26

Transitioning border for a hover state. Simple, right? You might be unpleasantly surprised.

The Challenge

The challenge is simple: building a button with an expanding border on hover.

This article will focus on genuine CSS tricks that would be easy to drop into any project without having to touch the DOM or use JavaScript. The methods covered here will follow these rules

  • Single element (no helper divs, but psuedo-elements are allowed)
  • CSS only (no JavaScript)
  • Works for any size (not restricted to a specific width, height, or aspect ratio)
  • Supports transparent backgrounds
  • Smooth and performant transition

I proposed this challenge in the Animation at Work Slack and again on Twitter. Though there was no consensus on the best approach, I did receive some really clever ideas by some phenomenal developers.

Method 1: Animating border

The most straightforward way to animate a border is… well, by animating border.

.border-button { border: solid 5px #FC5185; transition: border-width 0.6s linear; } .border-button:hover { border-width: 10px; }

Nice and simple, but there are some big performance issues.

Since border takes up space in the document’s layout, changing the border-width will trigger layout. Nearby elements will shift around because of the new border size, making browser reposition those elements every frame of the animation unless you set an explicit size on the button.

As if triggering layout wasn’t bad enough, the transition itself feels “stepped”. I’ll show why in the next example.

Method 2: Better border with outline

How can we change the border without triggering layout? By using outline instead! You’re probably most familiar with outline from removing it on :focus styles (though you shouldn’t), but outline is an outer line that doesn’t change an element’s size or position in the layout.

.border-button { outline: solid 5px #FC5185; transition: outline 0.6s linear; margin: 0.5em; /* Increased margin since the outline expands outside the element */ } .border-button:hover { outline-width: 10px; }

A quick check in Dev Tools’ Performance tab shows the outline transition does not trigger layout. Regardless, the movement still seems stepped because browsers are rounding the border-width and outline-width values so you don’t get sub-pixel rendering between 5 and 6 or smooth transitions from 5.4 to 5.5.

Strangely, Safari often doesn’t render the outline transition and occasionally leaves crazy artifacts.

Method 3: Cut it with clip-path

First implemented by Steve Gardner, this method uses clip-path with calc to trim the border down so on hover we can transition to reveal the full border.

.border-button { /* Full width border and a clip-path visually cutting it down to the starting size */ border: solid 10px #FC5185; clip-path: polygon( calc(0% + 5px) calc(0% + 5px), /* top left */ calc(100% - 5px) calc(0% + 5px), /* top right */ calc(100% - 5px) calc(100% - 5px), /* bottom right */ calc(0% + 5px) calc(100% - 5px) /* bottom left */ ); transition: clip-path 0.6s linear; } .border-button:hover { /* Clip-path spanning the entire box so it's no longer hiding the full-width border. */ clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%); }

clip-path technique is the smoothest and most performant method so far, but does come with a few caveats. Rounding errors may cause a little unevenness, depending on the exact size. The border also has to be full size from the start, which may make exact positioning tricky.

Unfortunately there’s no IE/Edge support yet, though it seems to be in development. You can and should encourage Microsoft’s team to implement those features by voting for masks/clip-path to be added.

Method 4: linear-gradient background

We can simulate a border using a clever combination of multiple linear-gradient backgrounds properly sized. In total we have four separate gradients, one for each side. The background-position and background-size properties get each gradient in the right spot and the right size, which can then be transitioned to make the border expand.

.border-button { background-repeat: no-repeat; /* background-size values will repeat so we only need to declare them once */ background-size: calc(100% - 10px) 5px, /* top & bottom */ 5px calc(100% - 10px); /* right & left */ background-position: 5px 5px, /* top */ calc(100% - 5px) 5px, /* right */ 5px calc(100% - 5px), /* bottom */ 5px 5px; /* left */ /* Since we're sizing and positioning with the above properties, we only need to set up a simple solid-color gradients for each side */ background-image: linear-gradient(0deg, #FC5185, #FC5185), linear-gradient(0deg, #FC5185, #FC5185), linear-gradient(0deg, #FC5185, #FC5185), linear-gradient(0deg, #FC5185, #FC5185); transition: all 0.6s linear; transition-property: background-size, background-position; } .border-button:hover { background-position: 0 0, 100% 0, 0 100%, 0 0; background-size: 100% 10px, 10px 100%, 100% 10px, 10px 100%; }

This method is quite difficult to set up and has quite a few cross-browser differences. Firefox and Safari animate the faux-border smoothly, exactly the effect we’re looking for. Chrome’s animation is jerky and even more stepped than the outline and border transitions. IE and Edge refuse to animate the background at all, but they do give the proper border expansion effect.

Method 5: Fake it with box-shadow

Hidden within box-shadow's spec is a fourth value for spread-radius. Set all the other length values to 0px and use the spread-radius to build your border alternative that, like outline, won’t affect layout.

.border-button { box-shadow: 0px 0px 0px 5px #FC5185; transition: box-shadow 0.6s linear; margin: 0.5em; /* Increased margin since the box-shado expands outside the element, like outline */ } .border-button:hover { box-shadow: 0px 0px 0px 10px #FC5185; }

The transition with box-shadow is adequately performant and feels much smoother, except in Safari where it’s snapping to whole-values during the transition like border and outline.

Pseudo-Elements

Several of these techniques can be modified to use a pseudo-element instead, but pseudo-elements ended up causing some additional performance issues in my tests.

For the box-shadow method, the transition occasionally triggered paint in a much larger area than necessary. Reinier Kaper pointed out that a psuedo-element can help isolate the paint to a more specific area. As I ran further tests, box-shadow was no longer causing paint in large areas of the document and the complication of the pseudo-element ended up being less performant. The change in paint and performance may have been due to a Chrome update, so feel free to test for yourself.

I also could not find a way to utilize psuedo-elements in a way that would allow for transform based animation.

Why not transform: scale?

You may be firing up Twitter to helpfully suggest using transform: scale for this. Since transform and opacity are the best style properties to animate for performance, why not use a pseudo-element and have the border scale up & down?

.border-button { position: relative; margin: 0.5em; border: solid 5px transparent; background: #3E4377; } .border-button:after { content: ''; display: block; position: absolute; top: 0; right: 0; bottom: 0; left: 0; border: solid 10px #FC5185; margin: -15px; z-index: -1; transition: transform 0.6s linear; transform: scale(0.97, 0.93); } .border-button:hover::after { transform: scale(1,1); }

There are a few issues:

  1. The border will show through a transparent button. I forced a background on the button to show how the border is hiding behind the button. If your design calls for buttons with a full background, then this could work.
  2. You can’t scale the border to specific sizes. Since the button’s dimensions vary with the text, there’s no way to animate the border from exactly 5px to 10px using only CSS. In this example I’ve done some magic-numbers on the scale to get it to appear right, but that won’t be universal.
  3. The border animates unevenly because the button’s aspect ratio isn’t 1:1. This usually means the left/right will appear larger than the top/bottom until the animation completes. This may not be an issue depending on how fast your transition is, the button’s aspect ratio, and how big your border is.

If your button has set dimensions, Cher pointed out a clever way to calculate the exact scales needed, though it may be subject to some rounding errors.

Beyond CSS

If we loosen our rules a bit, there are many interesting ways you can animate borders. Codrops consistently does outstanding work in this area, usually utilizing SVGs and JavaScript. The end-results are very satisfying, though they can be a bit complex to implement. Here are a few worth checking out:

Conclusion

There’s more to borders than simply border, but if you want to animate a border you may have some trouble. The methods covered here will help, though none of them are a perfect solution. Which you choose will depend on your project’s requirements, so I’ve laid out a comparison table to help you decide.

My recommendation would be to use box-shadow, which has the best overall balance of ease-of-implementation, animation effect, performance and browser support.

Do you have another way of creating an animated border? Perhaps a clever way to utilize transforms for moving a border? Comment below or reach me on Twitter to share your solution to the challenge.

Special thanks to Martin Pitt, Steve Gardner, Cher, Reinier Kaper, Joseph Rex, David Khourshid, and the Animation at Work community.

Animating Border is a post from CSS-Tricks

A Front End Developer’s Guide to GraphQL

Mon, 12/04/2017 - 14:21

No matter how large or small your application is, you’ll have to deal with fetching data from a remote server at some point. On the front end, this usually involves hitting a REST endpoint, transforming the response, caching it, and updating your UI. For years, REST has been the status quo for APIs, but over the past year, a new API technology called GraphQL has exploded in popularity due to its excellent developer experience and declarative approach to data fetching.

In this post, we’ll walk through a couple of hands-on examples to show you how integrating GraphQL into your application will solve many pain points working with remote data. If you’re new to GraphQL, don’t panic! I’ll also highlight some resources to help you learn GraphQL using the Apollo stack, so you can start off 2018 ahead of the curve.

GraphQL 101

Before we dive into how GraphQL makes your life as a front end developer easier, we should first clarify what it is. When we talk about GraphQL, we're either referring to the language itself or its rich ecosystem of tools. At its core, GraphQL is a typed query language developed by Facebook that allows you to describe your data requirements in a declarative way. The shape of your result matches the shape of your query: in the example below, we can expect to receive back an object with a currency property and a rates property containing an array of objects with both currency and rate keys.

{ rates(currency: "USD") { currency rates { currency rate } } }

When we talk about GraphQL in a broader sense, we’re often referring to the ecosystem of tools that help you implement GraphQL in your application. On the backend, you’ll use Apollo Server to create a GraphQL server, which is a single endpoint that parses a GraphQL request and returns data. How does the server know which data to return? You’ll use GraphQL Tools to build a schema (like a blueprint for your data) and a resolver map (just a series of functions that retrieve your data from a REST endpoint, database, or wherever else you choose).

This all sounds more complicated than it actually is — with Apollo Launchpad, a GraphQL server playground, you can create a working GraphQL server in your browser in less than 60 lines of code! &#x1f62e; We’ll reference this Launchpad I created that wraps the Coinbase API throughout this post.

You’ll connect your GraphQL server to your application with Apollo Client, a fast and flexible client that fetches, caches, and updates your data for you. Since Apollo Client isn’t coupled to your view layer, you can use it with React, Angular, Vue, or plain JavaScript. Not only is Apollo cross-framework, it’s also cross-platform, with React Native & Ionic supported out of the box.

Let’s give it a try! &#x1f680;

Now that you’re well-versed in what GraphQL is, let’s get our hands dirty with a couple of practical examples that illustrate what it’s like to develop your front end with Apollo. By the end, I think you’ll be convinced that a GraphQL-based architecture with Apollo can help you ship features faster than before.

1. Add new data requirements without adding a new endpoint

We’ve all been here before: You spend hours building a perfect UI component when suddenly, product requirements change. You quickly realize that the data you need to fulfill these new requirements would either require a complicated waterfall of API requests or worse, a new REST endpoint. Now blocked on your work, you ask the backend team to build you a new endpoint just to satisfy the data needs for one component.

This common frustration no longer exists with GraphQL because the data you consume on the client is no longer coupled to an endpoint’s resource. Instead, you always hit the same endpoint for your GraphQL server. Your server specifies all of the resources it has available via your schema and lets your query determine the shape of the result. Let’s illustrate these concepts using our Launchpad from before:

In our schema, look at lines 22–26 where we define our ExchangeRate type. These fields list out all the available resources we can query in our application.

type ExchangeRate { currency: String rate: String name: String }

With REST, you’re limited to the data your resource provides. If your /exchange-rates endpoint doesn’t include name, then you’ll need to either hit a different endpoint like /currency for the data or create it if it doesn’t exist.

With GraphQL, we know that name is already available to us by inspecting our schema, so we can query for it in our application. Try running this example in Launchpad by adding the name field on the right side panel!

{ rates(currency: "USD") { currency rates { currency rate name } } }

Now, remove the name field and run the same query. See how the shape of our result changes?

Your GraphQL server always gives you back exactly the data you ask for. Nothing more. This differs significantly from REST, where you often have to filter and transform the data you get back from the server into the shape your UI components need. Not only does this save you time, it also results in smaller network payloads and CPU savings from loading and parsing the response.

2. Reduce your state management boilerplate

Fetching data almost always involves updating your application’s state. Typically, you’ll write code to track at least three actions: one for when the data is loading, one if the data successfully arrives, and one if the data errors out. Once the data arrives, you have to transform it into the shape your UI components expect, normalize it, cache it, and update your UI. This process can be repetitive, requiring countless lines of boilerplate to execute one request.

Let’s see how Apollo Client eliminates this tiresome process altogether by looking at an example React app in CodeSandbox. Navigate to `list.js` and scroll to the bottom.

export default graphql(ExchangeRateQuery, { props: ({ data }) => { if (data.loading) { return { loading: data.loading }; } if (data.error) { return { error: data.error }; } return { loading: false, rates: data.rates.rates }; } })(ExchangeRateList);

In this example, React Apollo, Apollo Client’s React integration, is binding our exchange rate query to our ExchangeRateList component. Once Apollo Client executes that query, it tracks loading and error state automatically and adds it to the data prop. When Apollo Client receives the result, it will update the data prop with the result of the query, which will update your UI with the rates it needs to render.

Under the hood, Apollo Client normalizes and caches your data for you. Try clicking some of the currencies in the panel on the right to watch the data refresh. Now, select a currency a second time. Notice how the data appears instantaneously? That’s the Apollo cache at work! You get all of this for free just by setting up Apollo Client with no additional configuration. &#x1f60d; To see the code where we initialize Apollo Client, check out `index.js`.

3. Debug quickly & painlessly with Apollo DevTools & GraphiQL

It looks like Apollo Client does a lot for you! How do we peek inside to understand what’s going on? With features like store inspection and full visibility into your queries & mutations, Apollo DevTools not only answers that question, but also makes debugging painless and, dare I say it, fun! &#x1f389; It’s available as an extension for both Chrome and Firefox, with React Native coming soon.

If you want to follow along, install Apollo DevTools for your preferred browser and navigate to our CodeSandbox from the previous example. You’ll need to run the example locally by clicking Download in the top nav bar, unzipping the file, running npm install, and finally npm start. Once you open up your browser’s dev tools panel, you should see a tab that says Apollo.

First, let’s check out our store inspector. This tab mirrors what’s currently in your Apollo Client cache, making it easy to confirm your data is stored on the client properly.

Apollo DevTools also enables you to test your queries & mutations in GraphiQL, an interactive query editor and documentation explorer. In fact, you already used GraphiQL in the first example where we experimented with adding fields to our query. To recap, GraphiQL features auto-complete as you type your query into the editor and automatically generated documentation based on GraphQL’s type system. It’s extremely useful for exploring your schema, with zero maintenance burden for developers.

Try executing queries with GraphiQL in the right side panel of our Launchpad. To show the documentation explorer, you can hover over fields in the query editor and click on the tooltip. If your query runs successfully in GraphiQL, you can be 100% positive that the same query will run successfully in your application.

Level up your GraphQL skills

If you made it to this point, awesome job! &#x1f44f; I hope you enjoyed the exercises and got a taste of what it would be like to work with GraphQL on the front end.

Hungry for more? &#x1f32e; Make it your 2018 New Year’s resolution to learn more about GraphQL, as I expect its popularity to grow even more in the upcoming year. Here’s an example app to get you started featuring the concepts we learned today:

Go forth and GraphQL (and be sure to tag us on Twitter @apollographql along the way)! &#x1f680;

A Front End Developer’s Guide to GraphQL is a post from CSS-Tricks

The Three Developers and the Insightful User Tester

Sun, 12/03/2017 - 21:17

A story by Scott O'Hara:

The first of the developers, why he thought he knew best.
“I’ll get this done ever so quick!” he said, puffing out his chest.

“While the others review wikis, knowledge bases, and specifications,
I’ll lean on my deep knowledge of CSS to circumvent such onerous proclamations.

Specificity will be lax, and BEM classes will be king!
Everyone will marvel at the CSS of this thing.

Direct Link to ArticlePermalink

The Three Developers and the Insightful User Tester is a post from CSS-Tricks

A Big List of Typography Books

Sun, 12/03/2017 - 00:56

For your holiday gift shopping needs! These my picks for some of the most popular books out there on typography, with a tilt toward web typography. Plus a couple of bonus picks by our own Robin Rendle.

Direct Link to ArticlePermalink

A Big List of Typography Books is a post from CSS-Tricks

24 Ways

Sat, 12/02/2017 - 04:02

24 Ways, the advent calendar for web geeks, started up again this week. Throughout December they’ll be publishing a wide range of posts all about web design, CSS, and front-end development.

Chen Hui Jing has already written a great post about feature queries and Stephanie Drescher published a post today about a tool called sonarwhal which identifies accessibility, performance and security issues, just to name a few.

And if you're into advent calendars, here's another 16 web development related ones.

Direct Link to ArticlePermalink

24 Ways is a post from CSS-Tricks

How the Roman Empire Made Pure CSS Connect 4 Possible

Fri, 12/01/2017 - 20:09

Experiments are a fun excuse to learn the latest tricks, think of new ideas, and push your limits. "Pure CSS" demos have been a thing for a while, but new opportunities open up as browsers and CSS itself evolves. CSS and HTML preprocessors also helped the scene move forward. Sometimes preprocessors are used for hardcoding every possible scenario, for example, long strings of :checked and adjacent sibling selectors.

In this article, I will walk through the key ideas of a Pure CSS Connect 4 game I built. I tried to avoid hardcoding as much as I could in my experiment and worked without preprocessors to focus on keeping the resulting code short. You can see all the code and the game right here:

See the Pen Pure CSS Connect 4 by Bence Szabó (@finnhvman) on CodePen.

Essential concepts

I think there are some concepts that are considered essential in the "pure CSS" genre. Typically form elements are used for managing state and capturing user actions. I was excited when I found people use <button type="reset"> to reset or start a new game. All you have to do is wrap your elements in a <form> tag and add the button. In my opinion this is a much cleaner solution than having to refresh the page.

My first step was to create a form element then throw a bunch of inputs into it for the slots and add the reset button. Here is a very basic demonstration of <button type="reset"> in action:

See the Pen Pure HTML Form Reset by Bence Szabó (@finnhvman) on CodePen.

I wanted to have nice visual for this demo to provide a full experience. Instead of pulling in an external image for the board or the discs, I used a radial-gradient(). A nice resource I often use is Lea Verou's CSS3 Patterns Gallery. It is a collection of patterns made by gradients, and they're editable too! I used currentcolor, which came pretty handy for the disc pattern. I added a header and reused my Pure CSS Ripple Button.

At this point the layout and disc design was already final, only the game didn't work at all Dropping discs onto the board

Next I enabled users to take their turns dropping discs onto the Connect 4 board. In Connect 4, players (one red and one yellow) drop discs into columns in alternating turns. There are 7 columns and 6 rows (42 slots). Each slot can be empty or occupied by a red or yellow disc. So, a slot can have three states (empty, red, or yellow). Discs dropped in the same column are stacked onto each other.

I started out by placing two checkboxes for each slot. When they're both unchecked the slot is considered empty, and when one of them is checked the corresponding player has its disc in it.

The possible state of having them both checked should be avoided by hiding them once either of them is checked. These checkboxes are immediate siblings, so when the first of a pair is checked you can hide both by using :checked pseudo-class and the adjacent sibling combinator (+). What if the second is checked? You can hide the second one, but how to affect the first one? Well, there is no previous sibling selector, that's just not how CSS selectors work. I had to reject this idea.

Actually, a checkbox can have three states by itself, it can be in the indeterminate state. The problem is that you can't put it into indeterminate state with HTML alone. Even if you could, the next click on the checkbox would always make it transform into checked state. Forcing the second player to double-click when they make their move is unreliable and unacceptable.

I was stuck on the MDN doc of :indeterminate and noticed that radio inputs also have indeterminate state. Radio buttons with the same name are in this state when they're all unchecked. Wow, that's an actual initial state! What's really beneficial is that checking the latter sibling also has an effect on the former one! Thus I filled the board with 42 pairs of radio inputs.

In retrospect, clever ordering and usage of labels with either checkboxes or radio buttons would have made the trick, but I didn't consider labels to be an option to keep the code simpler and shorter.

I wanted to have large areas for interaction to have nice UX, so I thought it's reasonable to let players make a move by clicking on a column. I stacked controls of the same column on each other by adding absolute and relative positioning to the appropriate elements. This way only the lowest empty slot could be selected within a column. I meticulously set the time of transition of disc fall per row and their timing function is approximating a quadratic curve to resemble realistic free fall. So far the pieces of the puzzle came well together, though the animation below clearly shows that only the red player could make their moves.

Even though all the controls are there, only red discs can be dropped on the board

The clickable areas of radio inputs are visualized with colored but semi-transparent rectangles. The yellow and red inputs are stacked over each other six times(=six rows) per column, leaving the red input of the lowest row on top of the stack. The mixture of red and yellow creates the orangish color which can be seen on the board at start. The less empty slots are available in a column, the less intense this orangish color gets since the radio inputs are not displayed once they are not :indeterminate. Due to the red input always being precisely over the yellow input in every slot, only the red player is able to make moves.

Tracking turns

I only had a faint idea and a lot of hope that I can somehow solve switching turns between the two players with the general sibling selector. The concept was to let the red player take turn when the number of checked inputs was even (0, 2, 4, etc.) and let the yellow player take turn when that number was odd. Soon I realized that the general sibling selector does not (and should not!) work the way I wanted.

Then a very obvious choice was to experiment with the nth selectors. However attracting it was to use the even and odd keywords, I ran into a dead end. The :nth-child selector "counts" the children within a parent, regardless of type, class, pseudo-class, whatever. The :nth-of-type selector "counts" children of a type within a parent, regardless of class or pseudo-class. So the problem is that they cannot count based on the :checked state.

Well CSS counters count too, so why not give them a try? A common usage of counters is to number headings (even in multiple levels) in a document. They are controlled by CSS rules, can be arbitrarily reset at any point and their increment (or decrement!) values can be any integer. The counters are displayed by the counter() function in the content property.

The easiest step was to set up a counter and count the :checked inputs in the Connect 4 grid. There are only two difficulties with this approach. The first is you cannot perform arithmetics on a counter to detect if its is even or odd. The second is that you cannot apply CSS rules to elements based on the counter value.

I managed to overcome the first issue by making the counter binary. The value of the counter is initially zero. When the red player checks their radio button the counter is incremented by one. When the yellow player checks their radio button the counter is decremented by one, and so on. Therefore the counter value will be either zero or one, even or odd.

Solving the second problem required much more creativity (read: hack). As mentioned counters can be displayed, but only in the ::before and ::after pseudo-elements. That is a no-brainer, but how can they affect other elements? At the very least the counter value can change the width of the pseudo-element. Different numbers have different widths. Character 1 is typically thinner than 0, but that is something very hard to control. If the number of characters change rather than the character itself the resulting width change is more controllable. It is not uncommon to use Roman numerals with CSS counters. One and two represented in Roman numerals are the same character once and twice and so are their widths in pixels.

My idea was to attach the radio buttons of one player (yellow) to the left, and attach the radio buttons of the other player (red) to the right of their shared parent container. Initially, the red buttons are overlaid on the yellow buttons, then the width change of the container would cause the red buttons to "go away" and reveal the yellow buttons. A similar real-world concept is the sliding window with two panes, one pane is fixed (yellow buttons), the other is slidable (red buttons) over the other. The difference is that in the game only half of the window is visible.

So far, so good, but I still wasn't satisfied with font-size (and the other font properties) indirectly controlling the width. I thought letter-spacing would fit nicely here, since it only increases the size in one dimension. Unexpectedly, even one letter has letter spacing (which is rendered after the letter), and two letters render the letter spacing twice. Predictable widths are crucial to make this reliable. Zero width characters along with single and double letter spacing would work, but it is dangerous to set the font-size to zero. Defining large letter-spacing (in pixels) and tiny (1px) font-size made it almost consistent across all browsers, yes I'm talking about sub-pixels.

I needed the container width to alternate between initial size (=w) and at least double the initial size (>=2w) to be able to fully hide and show the yellow buttons. Let's say v is the rendered width of the 'i' character (lower roman representation, varies across browsers), and c is the rendered width (constant) of the letter-spacing. I needed v + c = w to be true but it couldn't be, because c and w are integers but v is non-integer. I ended up using min-width and max-width properties to constrain the possible width values, so I also changed the possible counter values to 'i' and 'iii' to make sure the text widths underflow and overflow the constraints. In equations this looked like v + c < w, 3v + 3c > 2w, and v << c, which gives 2/3w < c < w. The conclusion is that the letter-spacing has to be somewhat smaller than the initial width.

I have been reasoning so far as if the pseudo element displaying the counter value was the parent of the radio buttons, it is not. However, I noticed that the width of the pseudo-element changes the width of its parent element, and in this case the parent is the container of the radio buttons.

If you are thinking couldn't this be solved with Arabic numerals? You are right, alternating the counter value between something like '1' and '111' would also work. Nevertheless, Roman numerals gave me the idea in the first place, and they were also a good excuse for the clickbaity title so I kept them.

The players take alternating turns starting with the red player

Applying the technique discussed makes the parent container of the radio inputs double in width when a red input is checked and makes it original width when a yellow input is checked. In the original width container the red inputs are over the yellow ones, but in the double width container, the red inputs are moved away.

Recognizing patterns

In real life, the Connect 4 board does not tell you if you have won or lost, but providing proper feedback is part of good user experience in any software. The next objective is to detect whether a player has won the game. To win the game a player has to have four of their discs in a column, row or diagonal line. This is a very simple task to solve in many programming languages, but in pure CSS world, this is a huge challenge. Breaking it down to subtasks is the way to approach this systematically.

I used a flex container as the parent of the radio buttons and discs. A yellow radio button, a red radio button and a div for the disc belong to a slot. Such a slot is repeated 42 times and arranged in columns that wrap. Consequently, the slots in a column are adjacent, which makes recognizing four in a column the easiest part using the adjacent selector:

<div class="grid"> <input type="radio" name="slot11"> <input type="radio" name="slot11"> <div class="disc"></div> <input type="radio" name="slot12"> <input type="radio" name="slot12"> <div class="disc"></div> ... <input type="radio" name="slot16"> <input type="radio" name="slot16"> <div class="disc"></div> <input type="radio" name="slot21"> <input type="radio" name="slot21"> <div class="disc"></div> ... </div> /* Red four in a column selector */ input:checked + .disc + input + input:checked + .disc + input + input:checked + .disc + input + input:checked ~ .outcome /* Yellow four in a column selector */ input:checked + input + .disc + input:checked + input + .disc + input:checked + input + .disc + input:checked ~ .outcome

This is a simple but ugly solution. There are 11 type and class selectors chained together per player to cover the case of four in a column. Adding a div with class of .outcome after the elements of the slots makes it possible to conditionally display the outcome message. There is also a problem with falsely detecting four in a column where the column is wrapped, but let's just put this issue aside.

A similar approach for detecting four in a row would be truly a terrible idea. There would be 56 selectors chained together per player (if I did the math right), not to mention that they would have a similar flaw of false detection. This is a situation where the :nth-child(An+B [of S]) or the column combinators will come handy in the future.

For better semantics one could add a new div for each column and arrange the slot elements in them. This modification would also eliminate the possibility of false detection mentioned above. Then detecting four in a row could go like: select a column where the first red radio input is checked, and select the adjacent sibling column where the first red radio input is checked, and so on two more times. This sounds very cumbersome and would require the "parent" selector.

Selecting the parent is not feasible, but selecting the child is. How would detecting four in a row go with available combinators and selectors? Select a column, then select its first red radio input if checked, and select the adjacent column, then select its first red radio input if checked, and so on two more times. It still sounds cumbersome, yet possible. The trick is not only in the CSS but also in the HTML, the next column has to be the sibling of the radio buttons in the previous column creating a nested structure.

<div class="grid column"> <input type="radio" name="slot11"> <input type="radio" name="slot11"> <div class="disc"></div> ... <input type="radio" name="slot16"> <input type="radio" name="slot16"> <div class="disc"></div> <div class="column"> <input type="radio" name="slot21"> <input type="radio" name="slot21"> <div class="disc"></div> ... <input type="radio" name="slot26"> <input type="radio" name="slot26"> <div class="disc"></div> <div class="column"> ... </div> </div> </div> /* Red four in a row selectors */ input:nth-of-type(2):checked ~ .column > input:nth-of-type(2):checked ~ .column > input:nth-of-type(2):checked ~ .column > input:nth-of-type(2):checked ~ .column::after, input:nth-of-type(4):checked ~ .column > input:nth-of-type(4):checked ~ .column > input:nth-of-type(4):checked ~ .column > input:nth-of-type(4):checked ~ .column::after, ... input:nth-of-type(12):checked ~ .column > input:nth-of-type(12):checked ~ .column > input:nth-of-type(12):checked ~ .column > input:nth-of-type(12):checked ~ .column::after

Well the semantics are messed up and these selectors are only for the red player (another round goes for the yellow player), on the other hand it does work. A little benefit is that there will be no falsely detected columns or rows. The display mechanism of the outcome also had to be modified, using the ::after pseudo element of any matching column is a consistent solution when proper styling is applied. As a result of this, a fake eighth column has to be added after the last slot.

As seen in the code snippet above, specific positions within a column are matched to detect four in a row. The very same technique can be used for detecting four in a diagonal by adjusting these positions. Note that the diagonals can are in two directions.

input:nth-of-type(2):checked ~ .column > input:nth-of-type(4):checked ~ .column > input:nth-of-type(6):checked ~ .column > input:nth-of-type(8):checked ~ .column::after, input:nth-of-type(4):checked ~ .column > input:nth-of-type(6):checked ~ .column > input:nth-of-type(8):checked ~ .column > input:nth-of-type(10):checked ~ .column::after, ... input:nth-of-type(12):checked ~ .column > input:nth-of-type(10):checked ~ .column > input:nth-of-type(8):checked ~ .column > input:nth-of-type(6):checked ~ .column::after

The number of selectors have increased vastly in the final run, and this is definitely a place where CSS preprocessors could reduce the length of the declaration. Still, I think the demo is moderately short. It should be somewhere around the middle on the scale from hardcoding a selector for every possible winning pattern to using 4 magical selectors (column, row, two diagonals).

A message is shown when a player wins Closing loopholes

Any software has edge cases and they need to be handled. The possible outcomes of a Connect 4 game are not only the red, or yellow player winning, but neither player winning filling the board known as draw. Technically this case doesn't break the game or produce any errors, what's missing is the feedback to the players.

The goal is to detect when there are 42 :checked radio buttons on the board. This also means that none of them are in the :indeterminate state. That is requiring a selection to be made for each radio group. Radio buttons are invalid, when they are :indeterminate, otherwise they are valid. So I added the required attribute for each input, then used the :valid pseudo-class on the form to detect draw.

The draw outcome message is shown when the board is filled

Covering the draw outcome introduced a bug. In the very rare case of the yellow player winning on last turn, both the win and draw messages are displayed. This is because the detection and display method of these outcomes are orthogonal. I worked around the issue by making sure that the win message has a white background and is over the draw message. I also had to delay the fade in transition of the draw message, so it would not get blended with the win message transition.

The yellow wins message is over the draw outcome preventing it to be displayed

While a lot of radio buttons are hid behind each other by absolute positioning, all of those in indeterminate state can still be accessed by tabbing through the controls. This enables players to drop theirs discs into arbitrary slots. A way to handle this is to simply forbid keyboard interactions by the tabindex attribute: setting it to -1 means that it should not be reachable via sequential keyboard navigation. I had to augment every radio input with this attribute to eliminate this loophole.

<input type="radio" name="slot11" tabindex="-1" required> <input type="radio" name="slot11" tabindex="-1" required> <div class="disc"></div> ... Limitations

The most substantial drawback is that the board isn't responsive and it might malfunction on small viewports due to the unreliable solution of tracking turns. I didn't dare to take the risk of refactoring to a responsive solution, due to the nature of the implementation it feels much safer with hardcoded dimensions.

Another issue is the sticky hover on touch devices. Adding some interaction media queries to the right places is the easiest way to cure this, though it would eliminate the free fall animation.

One might think that the :indeterminate pseudo-class is already widely supported, and it is. The problem is that it is only partially supported in some browsers. Observe Note 1 in the compatibility table: MS IE and Edge do not support it on radio buttons. If you view the demo in those browsers your cursor will turn into the not-allowed cursor on the board, this is an unintentional but somewhat graceful degradation.

Not all browsers support :indeterminate on radio buttons Conclusion

Thanks for making it to the last section! Let's see some numbers:

  • 140 HTML elements
  • 350 (reasonable) lines of CSS
  • 0 JavaScript
  • 0 external resources

Overall, I'm satisfied with the result and the feedback was great. I sure learned a lot making this demo and I hope I could share a lot writing this article!

How the Roman Empire Made Pure CSS Connect 4 Possible is a post from CSS-Tricks

Font of the Month Club

Thu, 11/30/2017 - 23:02

Every month for the past year, David Jonathan Ross has been publishing a new font to his Font of the Month Club. It’s only $6 for a monthly subscription and it provides early access to some of his work. I’d highly recommend signing up because each design is weird and intriguing in a very good way:

Join the Font of the Month Club and get a fresh new font delivered to your inbox every single month! Each font is lovingly designed and produced by me, David Jonathan Ross.

Fonts of the month are not available anywhere else, and will include my distinctive display faces, experimental designs, and exclusive previews of upcoming retail typeface families.

Direct Link to ArticlePermalink

Font of the Month Club is a post from CSS-Tricks

The Front-End Checklist is just a tool… everything depends on you.

Thu, 11/30/2017 - 21:41

One month ago, I launched the Front-End Checklist on GitHub. In less than 2 weeks, more than 10,000 people around the world starred the repository. That was completely unexpected and incredible!

I've been working as a front-end developer since 2011, but I started to build websites in 2000. Since then, like us all, I've been trying to improve the quality of my code and deliver websites faster. Along the way, I've been managing developers from two different countries. That has helped me to produce a checklist a little different than what I've found on around the web over the years.

While I was creating the checklist, I continuously had the book "The Checklist Manifesto: How to Get Things Right" by Atul Gawade in mind. That book has helped me build checklists for my work and personal life, and simplify things that sometimes seem too complex.

amzn_assoc_tracking_id = "csstricks-20"; amzn_assoc_ad_mode = "manual"; amzn_assoc_ad_type = "smart"; amzn_assoc_marketplace = "amazon"; amzn_assoc_region = "US"; amzn_assoc_design = "enhanced_links"; amzn_assoc_asins = "0312430000"; amzn_assoc_placement = "adunit"; amzn_assoc_linkid = "bc96260be7adede1459bf758a120d189";

If you are working alone or in a team, individually, remotely, or on-site, I wanted to share some advice on using the Front-End Checklist and the web application that goes with it. Perhaps I can convince you to integrate it into your development cycle.

#1 Decide which rules your project and team need to follow

Every project is different. Before starting a new project, the whole team (i.e. the project managers, designers, developers, QA, etc.) need to agree on what the deliverables will be.

To help you to decide, I created 3 different levels of priority: high, medium, and low. You don't necessarily need to agree with those distinctions, but they may help order your tasks.

The Front-End Checklist app was done to facilitate the creation of personalized checklists. Change some JSON files to your liking and you are ready to start!

#2 Define the rules to check at beginning, during, and at the end of your project

You shouldn't check all these rules only at the end of a project. You know as well as I do how projects are at the very end! Too hectic. Most of the items of the Front-End Checklist can be considered at the beginning of your development. It's up to you to decide. Make it clear to your team upfront what happens when.

#3 Learn a little more about each rules

Who loves reading the docs? Not most of us, but it's essential. If you want to understand the reasons for the rule, you can't avoid reading up about them. The more you understand the why of each rule, the better developer you become.

#4 Start to check!

The Front-End Checklist app can facilitate your life as a developer. It's a live checklist, so as you complete items your progress and grade are updated live. Everything is saved in localStorage so you can leave and come back as needed.

The project is open source, so feel free to fork it and use it however you like. I'm working on making sure all the files are commented. I especially invite those interested in Pug to take a look at the views folder.

#5 Integrate automated testing in your workflow

We all dream of automation (or is it just me?). For now, the Front-End Checklist is just an interactive list, but some of the tasks can be automated in your workflow.

Take a look at the gulpfile used to generate the project. All tasks are packages you can use with npm, webpack, etc.

#6 Validate every pages before sending to QA team and to production

If you're passionate about generating clean code and care about your code quality, you should be regularly testing your pages. It's so easy to make mistakes and remove some essential code. Or, someone else on your team might have done it, but it's your shared responsibilty to be catching things like that.

The Front-End Checklist can generate beautiful reports you can send to a project manager or Quality Assurance team.

#7 Enjoy your work above all

Some people might look at such a long checklist and feel sick to their stomach. Going through such a list might cause anxiety and really not be any fun.

But the Front-End Checklist is just a tool to help you deliver higher quality code. Code that affects all aspects of a project: the SEO, the user experience, the ROI, and ultimately the success of the project. A tool that can help across all those things might actually help reduce your anxiety and improve your health!

Conclusion

The success the Front-End Checklist received in such a short time reminded me that a lot of people are really interested in finding ways to improve their work. But just because the tool exists doesn't directly help with that. You also need to commit to using it.

In a time where AI is taking over many manual tasks, quality is a must-have. Even if automation takes over a lot of our tasks, some level of quality will remain impossible to automate, and us front-end developers still have many long days to enjoy our jobs.

The Front-End Checklist is just a tool… everything depends on you. is a post from CSS-Tricks

​7 Days of Free Stock Images

Thu, 11/30/2017 - 18:12

(This is a sponsored post.)

Storyblocks is exploding with over 400,000 stock photos, vectors, backgrounds and more! With its user friendly site, massive library to choose from, and fresh new content, there’s no stopping what you can do. All of the content is 100% free from any royalties. Anything you download is yours to keep and use forever! Right now you can get 7 days of free downloads. Get up to 20 photos, icons, and vectors everyday for 7 days. That's 140 downloads free over the course of the 7 days. Click on over and see where your imagination takes you! Start downloading now.

Direct Link to ArticlePermalink

​7 Days of Free Stock Images is a post from CSS-Tricks

Localisation and Translation on the Web

Thu, 11/30/2017 - 03:56

The other day Chris wrote about how the CodePen team added lang='en' to the html element in all pens for accessibility reasons and I thought it was pretty interesting but I suddenly wanted to learn more about that attribute because I’ve never designed a website in any other language besides English and it might be useful for the future.

As if by magic Ire Aderinokun published this piece on Localisation and Translation on the Web just a couple of days later and thankfully it answers all those questions I had:

Coming from the English-speaking world, it can be easy to maintain the bubble that is the English-speaking World Wide Web. But in fact, more than half of web pages are written in languages other than English.

Since starting work at eyeo, I’ve had to think a lot more about localisation and translations because most of our websites are translated into several languages, something I previously didn’t have to really consider before. Once you decide to translate a web page, there are many things to take into account, and a lot of them I've found are useful even if your website is written in only one language.

I had no idea about the experimental, and currently unsupported, translate attribute or the mysterious margin-inline-start CSS property. Handy stuff!

Direct Link to ArticlePermalink

Localisation and Translation on the Web is a post from CSS-Tricks

Fontastic Web Performance

Thu, 11/30/2017 - 03:54

In this talk Monica Dinculescu takes a deep dive into webfonts and how the font-display CSS property lets us control the way those fonts are rendered. She argues that there’s all sorts of huge performance gains to be had if we just spend a little bit of time thinking about the total number of fonts we load and how they’re loaded.

Also, Monica made a handy demo that gives an even more detailed series of examples of how the font-display property works:

This depends a lot on how you are using your webfont, and whether rendering the text in a fallback font makes sense. For example, if you're rendering the main body text on a site, you should use font-display:optional. On browsers that implement it, like Chrome, the experience will be much nicer: your users will get fast content, and if the web font download takes too long, they won't get a page relayout halfway through reading your article.

If you're using a web font for icons, there is no acceptable fallback font you can render these icons in (unless you're using emoji or something), so your only option is to completely block until the font is ready, with font-display:block.

Direct Link to ArticlePermalink

Fontastic Web Performance is a post from CSS-Tricks

WordPress + React

Wed, 11/29/2017 - 19:58

I posted just 2 months ago about Foxhound and how I found it pretty cool, but also curious that it was one of very few themes around that combine the WordPress JSON API and React, even though they seem like a perfect natural fit. Like a headless CMS, almost.

Since then, a few more things have crossed my desk of people doing more with this idea and combination.

Maxime Laboissonniere wrote Strapping React.js on a WordPress Backend: WP REST API Example:

I'll use WordPress as a backend, and WordPress REST API to feed data into a simple React e-commerce SPA:

  • Creating products with the WP Advanced Custom Fields plugin
  • Mapping custom fields to JSON payload
  • Consuming the JSON REST API with React
  • Rendering products in our store

Perhaps more directly usable, Postlight have put out a Starter Kit. Gina Trapani:

People who publish on the web love WordPress. Engineers love React. With some research, configuration, and trial and error, you can have both — but we’d like to save you the work.

Here's that repo.

WordPress + React is a post from CSS-Tricks

V6: Typography and Proportions

Tue, 11/28/2017 - 22:56

Here’s a good ol’ fashion blog post by Rob Weychert where he looks into the new design system that he implemented on his personal website and specifically the typographic system that ties everything together:

According to the OED, a scale is “a graduated range of values forming a standard system for measuring or grading something.” A piece of music using a particular scale—a limited selection of notes with a shared mathematic relationship—can effect a certain emotional tenor. Want to write a sad song? Use a minor scale. Changed your mind? Switch to a major scale and suddenly that same song is in a much better mood.

Spatial relationships can likewise achieve a certain visual harmony using similar principles, and the constraints a scale provides take a lot of the arbitrary guesswork out of the process of arranging elements in space. Most of what I design that incorporates type has a typographic scale as its foundation, which informs the typeface choices and layout proportions. The process of creating that scale begins by asking what the type needs to do, and what role contrasting sizes will play in that.

Direct Link to ArticlePermalink

V6: Typography and Proportions is a post from CSS-Tricks

An Idea for a Simple Responsive Spreadsheet

Tue, 11/28/2017 - 19:02

How do you make a spreadsheet-like interface responsive without the use of any JavaScript? This is the question I've been asking myself all week as I've been working on a new project and trying to figure out how to make the simplest spreadsheet possible. I wanted to avoid using a framework and instead, I decided to experiment with some new properties in order to use nothing but a light touch of CSS.

Spoilers! This is what I've come up with so far (oh and please note that this demo currently works in the latest version of Chrome). Try scrolling around a little bit:

See the Pen A Simple Responsive Spreadsheet – Final by Robin Rendle (@robinrendle) on CodePen.

Notice how the first column sticks to the left and the heading sticks to the top of the spreadsheet? This lets us scan lots of data without having to keep scrolling to figure out which column or row we're in — in a lot of interfaces like this it's pretty easy to get lost.

So how did I go about making this thing? Let's jump in!

Adding the markup

First we need to add our markup for the table and, just to make sure that this example is as realistic as possible, we're going to add a lot of rows and columns here:

See the Pen A Simple Responsive Spreadsheet – 1st by Robin Rendle (@robinrendle) on CodePen.

There's nothing really complex going on. We just have a regular ol' table with a <thead> and a <tbody>, but we do wrap the whole table in the table-wrapper div which I'll explain in just a little bit.

Next, we'll add basic styling to that wrapper element to move it into the center of the page and also give it a max-width. We also need to make sure that the .table-wrapper has overflow set to scroll, although at larger screen sizes we won't need that just yet:

body { display: flex; font-family: -apple-system; font-size: 90%; color: #333; justify-content: center; } .table-wrapper { max-width: 700px; overflow: scroll; }

See the Pen A Simple Responsive Spreadsheet – 2nd by Robin Rendle (@robinrendle) on CodePen.

Nifty! Now we can add styles for the first column of our table and the thead element as well as basic styling for each of the table cells:

table { border: 1px solid #ddd; border-collapse: collapse; } td, th { white-space: nowrap; border: 1px solid #ddd; padding: 20px; }

See the Pen A Simple Responsive Spreadsheet – 3 by Robin Rendle (@robinrendle) on CodePen.

The problem here is that we've now made a pretty inaccessible table; although we can scroll around in the spreadsheet we can't read which column or row is associated to which bit of data. This can lead to a table that is almost completely illegible and if we were to populate this with real data then it would be even worse:

position: sticky to the rescue!

position: sticky is a wonderfully handy CSS trick that I've started experimenting with a great deal lately. It lets you stick child elements to their parent containers so that as you scroll around the child element is always visible. And this is exactly what we need here for the first column and the heading of our table element.

We can use this relatively new feature with CSS like this:

// The heading of our table th { background-color: #eee; position: sticky; top: -1px; z-index: 2; // The first cell that lives in the top left of our spreadsheet &:first-of-type { left: 0; z-index: 3; } } // The first column that we want to stick to the left tbody tr td:first-of-type { background-color: #eee; position: sticky; left: -1px; z-index: 1; }

This z-index values are important here because we want the header to overlap the first left hand column that will also be sticky. However! We also want that empty cell at the top left to overlap both our header and our left hand column, like this:

See the Pen A Simple Responsive Spreadsheet – Final by Robin Rendle (@robinrendle) on CodePen.

But there we have it! A simple responsive spreadsheet where you can view both the heading and the first column no matter where you are in the table. Although, it's worth noting that your mileage may vary. position: sticky has relatively patchy support right now and so it's worth thoroughly testing before you start using it. Or you could use something like Stickybits that would act as a lightweight polyfill.

Also, if you need to dig into tables in more depth then we've made a rather handy Complete Guide to the Table Element.

An Idea for a Simple Responsive Spreadsheet is a post from CSS-Tricks

Introducing minmax()

Tue, 11/28/2017 - 19:00

It’s relatively easy to get lost in all the new features of CSS Grid because there’s just so much to learn and familiarize ourselves with; it’s much easier to learn it chunk by chunk in my opinion.

And so you might already be familiar with Rachel Andrew’s Grid By Example which contains a whole bunch of tutorials with new layout tips and tricks about CSS Grid. But the minmax() tutorial is one small chunk of Grid that you can learn today and thankfully Rachel has made a rather handy two minute long video that dives straight into it.

In fact, it’s pretty darn impressive how many opportunities just one new CSS feature can give us.

Direct Link to ArticlePermalink

Introducing minmax() is a post from CSS-Tricks

Pages