Rethinking CSS frameworks. 📖

Rethinking CSS frameworks. 📖

  • toucaan
  • 9 minutes
  • September 30, 2019

[Updated on: Jun, 09st 2020.]

These notes are available on a book.

Introduction

2020 is almost here.

It is unlikely that you and I are going to blast off to Mars or the Moon on a Spacex Starship anytime soon ever, so we better turn our gaze towards another frontier of technology:

CSS. 🙃

Let’s take a look at how we could use the new powers of CSS to write modern web applications of 2020 and beyond, here on Earth.

On this post, we will revisit the basics of a webpage, i.e. HTML & CSS, and develop a clean intelligent and maintainable CSS framework from scratch. I have named our new CSS framework Toucaan and you can join me on the journey of building it together.

Here is its official repository and a noddy Toucan logo that I made using CSS.


Toucaan-A Tropical CSS Framework

The Tropical CSS Framework.


Qualitatively speaking the intent of Toucaan is to weed out all the unwanted CSS that a framework doesn’t need anymore. It is a deep-dive into the core properties of CSS standards in a bid to discover new and useful patterns according to the new landscape of the web.

Who knows we might even identify a few industry-wide antipatterns in the process and we can address those with a few suggestions as we go about building Toucaan ground up.

Why call it Toucaan

Well, quite simply because I owned the pretty domain name.

Besides Toucan is a beautiful bird. This aggressive little arboreal ramphastidus symbolizes both beauty and strength. We are going to base our CSS framework on this highly social and resilient bird to implement a styling stricture that will cover all the wilderness on the web. Ocassionally—though rarely—we may even spar with other CSS frameworks using our “colorful, mean and oversized” bill.

So—say hello to Toucaan—the tropical CSS framework for the web. 😉

👉 CSS may be hard but… **if Tou-caan, then you can too!**



With Toucaan we will revisit every web design and layouting principle that there is. Test our ideas out in the open. No trick or technique, whether old or new is off the table, but we will certainly avoid using hacks. There are a few other rules that Toucaan will adhere to and those are described over here.

Now there are a lot of well-established CSS frameworks out there like the Bootstrap, Bulma, Foundation, TailwindCSS, and a bunch of strategies like the BEM, OOCSS, or SMACSS (and others) to organize the application code but we will not try to imitate or wrestle with those.

We will rather write Toucaan on a blank slate and in such a way that we do not take away most of what these tools have to offer, but we also end-up with more that is possible with what’s new on the table for everyone to use lately. On production.

Let’s begin.

New Landscape of The Web

Before we write our first line of code let us take a deep breath and look at the variety of devices that are a part of the web today. With subtle differences in their aspect ratios, device handling & user behavior, browser support, and screen-wise capabilities it is important to understand what the new landscape of the web looks like today and understand exactly what we are up against for the new framework of 2020.

Here are some of the devices that sport a modern web browser:

Major web devices.
Major web devices.


There is the Apple Watch 5 with a Webkit browser and the iPhones are available in numerous sizes instead of just the one model that Apple used to promote earlier. There are multiple iPads and iPad Pros, a slew of Android tablets of different form-factors plus the desktops, laptops, and touchscreen tablet-PCs.

Smart televisions like the LG OLED series (and many others) come with a solid stock browser and a pointer driven UI as well. Given that Samsung came out with a foldable phone recently and Microsoft has is probably coming out with outed a foldable Surface tablet, it is rather safe to assume that screens available today are on a linear continuum of size and form-factor.

That the slate of glass is practically resizable freely just like the desktop browser itself.

And the web is no longer tied to a “mobile-first” paradigm alone.

One can easily consider a large phone a tablet (phablet?) or a tablet could easily be turned into a desktop with options. While there is a large variety of devices that are available on the web today, there is also a great difference in the behavior, the way users interact with each of these devices—–ala, subtle differences in controls and input methods, accessibility over the content.

Other than that there are cars too on the web—–in that, smartcars sport a neat web browser for those who need to be online on road. And low-powered devices on the budget end of the market, like the Nokia 2.2 on Android (with A53 core) or similar that are very popular in their segment.


Major web devices.
Credit: Stuart O'Neil, The Noun Project.


Since Toucaan is about living CSS a short distance into the future, we will consider the V9 web browser on Tesla into the scope of our project as well. This is something that I have been meaning to do for quite some time and given that people will have nothing to do but surf the web or read a book in a self-driving car, this sounds like a reasonable thing to do.


Major web devices.
Web is way bigger than it ever was.


Quick note: I wanted to publish this article three> years ago but the rate of change in the industry kept me from doing so. With new features being rolled out every week it was hard to keep up and decide on a strategy. CSS grids or Flexbox, ES6 or not, and that whole reactive developer toolchain thing. All those “developer happiness” bits kept flowing while Apple & Google announced a non-rectangular notched phones upsetting my plans to do a paced research.

The web is enormous now and it is no doubt much harder to design and scale web-apps between the lowest and the highest options available today.

Notice that we are not even talking about browsers inconsistencies at this point. The range of hardware itself is wide enough to somewhat trump the very first assumption taken by nearly all the major CSS frameworks:

“Hardcoded breakpoints on CSS @media-queries”.

Voila, and now we have our first anti-pattern to go after! ( ͡° ͜ʖ ͡°)

Media Queries with hardcoded breakpoints

Breakpoints are hardcoded on Tailwind CSS like this [1, 2], for example.

// tailwind.config.js
module.exports = {
  theme: {
    screens: {
      'sm': '640px', // Translates to hardcoded break-points in media queries.
      'md': '768px',
      'lg': '1024px',
      'xl': '1280px',
    }
  }
}

On Bulma, the breakpoints [1] are used similarly to silo the blocks of css code like so:

/* Bulma CSS like any other framework uses hardcoded breakpoints like so: */

@media screen and (max-width: 768px) { /* Some style classes & rules here. */ }

@media screen and (min-width: 769px), print { /* Same classNames but different rules here. */ }

@media screen and (max-width: 1023px) { /* We armtwist the ruleset again… */ }

@media screen and (min-width: 1024px) { /* Are we on the desktops now? */ }

@media screen and (min-width: 1216px) { /* Dang!, what are we supporting here? */ }

@media screen and (min-width: 1408px) { /* Is this the iPad Pro 12.9 inches or something else? */ }

Then for each silo this happens on the CSS elsewhere…

+mobile
  +typography-size('mobile')

+tablet
  +typography-size('tablet')

+touch
  +typography-size('touch')

+desktop
  +typography-size('desktop')

+widescreen
  +typography-size('widescreen')

+fullhd
  +typography-size('fullhd')

Bootstrap does the same thing… and then thousands of utility classNames are repeated on each silo of devices to cater to the behavior desired of that group.

Pretty much every CSS framework follows this pattern and a new breakpoint is added every few years to account for industry-level changes. The question is how many breakpoints will cover the new landscape of the web now?

Can we continue this way as the industry continues to evolve at a break-neck speed.

At what point will the hardcoded breakpoints become all too many?

Mode-driven instead of data-driven:

While it would be a nice exercise to plot a graph of all the screen sizes (pixel ratio data) that are available on the market, but going down this path to figure out the ideal set of breaking point values to separate watches from mobile from tablets from desktops from cars to any other larger surface that is about to come on the web is anything but scalable. Or even practical.

In my opinion, using hardcoded values on CSS media queries is an artifact of the mobile-web. A result from the tunnel vision that we have had of the web since the very first iPhone. It is a simplistic solution from a simpler time that is no longer valid today.

An anti-pattern that should be done away with.

So, is there a way to implement layout responsively without using hardcoded break-points?

Turns out, there is!

We can build any kind of responsive application using a really simple and smart set of rules that we will talk about in the next section.

The Two States of Web Design.

There are only two states of web-design. Let’s see how:

Ccreate a blank page on your machine and load it on a browser (desktop) first.

This is easy enough, simply jump into the terminal and:

$ touch example0.html     // Create a new file but do not write anything on it.

$ chrome example0.html    // Open this 0 byte files on your favorite browser.

What do you see on this blank page?

Of course nothing. It is an all-white or an all-black blank page depending on settings. Did you know that this blank webpage is already responsive?

No CSS or media-query is required to adapt the UX/UI of a blank page on mobile or desktop or any other web device. You can resize the browser to any size or aspect ratio and the blank page will continue to scale accurately.

It’s perfectly responsive, and just “belongs to” the device naturally. Intrinsically.


Major web devices.
Viewport rectangles of the browser window on resize.


Let’s switch gears and mount the desktop in portrait mode instead:



Now the rectangular screen is in portrait orientation so the browser window will appear longer in height—kind of like a mobile phone but on a much bigger piece of glass. The blank webpage would scale here too!

Only a small group of developers are known to use the desktop monitor in portrait mode but the usage is certainly possible. I have seen monitors mounted vertically at the airports and above POS counters like that of McDonalds, for example.

The usage of the portrait mode grows as the size of the screen shrinks. About 40% iPad users, for example, prefer portrait orientation over landscape whereas the story flips completely on mobile where almost ~96% people prefer the portrait orientation.

With the Apple Watch, the tiniest of viewports, there isn’t even a landscape mode given that the device is physically tied to the wrist that way.

Here are some graphs & stats if you’re interested.

On a Model S (Tesla) the browser opens in portrait orientation just like a vertically mounted desktop whereas on a Model 3 it does so in landscape mode.

From the discussion above it is clear that the web is viewed in only two kinds of rectangles—a portrait rectangle or a landscape one, with the square being the point of inflection for the geometry to switch. Interesting.

This also means that there are only two states of web design no matter which device a user may choose to surf on. It is a cold hard fact that electronic screens are always rectangular—well, almost—and therefore, all our stylistic choices and design philosophy should optimize towards the two states independently and orthogonally.

The point where the viewport/window becomes a perfect square, our media-query needs to switch and start flexing in the other direction. Since there are hardly any devices in the shape of a perfect square, we can grant that a webpage will render either in portrait mode or the landscape only.


And oh, ICYMI, there is a lot more math coming into CSS in the near future so we’ll have trigonometry at our disposal eventually!


Kickstarting the code

Now that we have covered some ground for Toucaan to work on let’s start wiring up all the ideas discussed above into code. Since a webpage can be rendered in only one of the two states of the viewport, either portrait or landscape, we’ll begin with the following ruleset (scss):


/* scss */

@import url('toucaan/portrait/portrait.css') only screen and (orientation: portrait);

@import url('toucaan/landscape/landscape.css') only screen and (orientation: landscape);

@media only screen and (orientation: portrait) {
  :root { 
    /* Portrait variables go here. */ 
  }
}

@media only screen and (orientation: landscape) {
  :root { 
    /* Landscape variables go here. */ 
  }
}

The twin code blocks above may not seem like much at this stage but this dual state switch is exactly what we are going to use to go about scaling Toucaan with. Scale layouts across all the web devices on the planet along two orthogonal axes––i.e. two states of design.

Notice that we are using a standard asynchronous @import call to request only so much CSS that a given viewport or design “state” requires. It’s not like there is common css on another file that both orientations will requiere. On the desktop, a given render will not change shape unless the browser window is resized to extremes (in which case other state of design will activate) or the user decides to swivel the monitor over to portrait mode.

Organizing your CSS this way ensures that both orientations of every element that will render on the DOM have been considered and then we can be sure that the webpage will scale desirably across the entire spectrum of devices and browsers that are on the web. It also helps avoiding a gigantic reset.css/reboot.css which can be a pain to resolve on low-powered devices. So hang in there for a little bit and stand by for the next chapter on Toucaan in which we will take up baselining CSS across vendors and introduce scalable responsive typography without use of javascript.

I have setup a tiny repository for Toucaan and checked-in all that is under experimentation right now. Feel free to star, jump-in, offer sage advice or contribute to Toucan!


Written by: Marvin Danig, CEO & Cofounder of Bubblin Superbooks. Follow me on Twitter or Github?

Super thankful to Sonica Arora, Abigail Rennmeyer, Varun Singh and Nilesh Trivedi for helping me review this post for accuracies.

About the author

Marvin Danig

I write code with my bare hands. 💪🏻 Yammer about Bubblin all day.

https://bubblin.io/marvin