Refactoring CSS: The Three I’s

Refactoring CSS: The Three I’s

In a recent interview, I was asked about simple and/or replicable steps to take when refactoring CSS. The topics of legacy, Technical Debt, and refactoring are, for one reason or another, at the front of my mind at the moment, so I thought I would write up a short post on an approach to refactoring CSS (or any language) that I call The Three I’s: Identify, Isolate, Implement.

Identify

It’s all well and good knowing that ‘your CSS is a mess’, but which bits specifically? Which parts of your codebase are causing you problems right now? Which ones will be the quickest to refactor? Which parts will provide you with the most benefit once refactored? It is important to identify prime candidates for refactoring.

For example, the CSS for your nav might be cumbersome and hard to work with, but if the nav works correctly, is accessible, and you rarely have to edit the CSS for it, refactoring it will likely not provide you with much immediate value: we can probably afford to leave it as it is for a little while longer. However, your layout/grid system might be incredibly fragmented and inconsistent, it might have cross-browser issues, its responsiveness may have been bolted on as an afterthought, and of course it is probably used extensively and frequently. As a result, you might get a lot of value from tackling that first.

Have a clear idea of which parts of your project should be refactored, if at all.

Tip: Try to limit refactoring work to the scope of single features. It’s much safer to refactor a single feature than it is to refactor your entire naming convention, for example. For further detail on this, and much more, you can see my Refactoring CSS Without Losing Your Mind talk at a number of events throughout the rest of 2016.

Isolate

Once we have identified candidates for refactoring, we need to isolate them before and during working on them. Suppose we have decided to refactor our layout system first, we should rewrite this in isolation, outside of our project.

In order to do this, open a new jsFiddle, CodePen, etc. and begin work there. Do not refactor features back into a stale codebase, as doing so runs the risk of making use of legacy CSS that may itself be refactored in future. For example, we might be using a traditional reset in the current project, which may be replaced by Normalize.css in future—we don’t want to build our brand new layout system on top of a reset that will be removed in six months time.

Build the new/refactored version of your feature in complete isolation so that you know it is well encapsulated, and it’s not making use of any legacy.

Implement

The final step is to implement your refactored feature. Copy and paste the jsFiddle CSS into the relevant part of your project, and see what happens. 90% of the time, you’ll find that there are some problems: conflicts with existing CSS, naming collisions, existing styles leaking into your new code, etc.

We tackle these details at implementation stage, and we need to give careful consideration as to where we place the fixes. If the fix solves a problem with the layout system itself, it is usually best to place the fix in the layout system’s partial. If the fix addresses problems arising from conflicts with legacy code, it is often best to place it in a shame.css file. This keeps the legacy fix away from greenfield CSS, meaning it will be much easier to remove once we’ve refactored whatever legacy was causing the problem in the first place.

Move the refactored feature back into the project and tidy things up here.

In short:

Identify sensible candidates for refactoring: not all legacy is born equal.
Isolate the feature in order to rebuild it: do not lean on out of date code.
Implement the refactored feature into the project: do any cleanup work at this point, and in the right place(s).


Localize Time with JavaScript

Localize Time with JavaScript

Say you have a time you’d like to display on your site. You’ve entered it in your time zone. You can always be specific and say something like: 3:00 PM Eastern Standard Time. Then leave it up to whoever is reading to convert it to their local time. Every Time Zone is a great site for that.

But it can be nice to localize the time for the reader. Time zone conversion is notoriously confusing. And it’s the type of thing computers are good at. JavaScript know what time zone the reader is in, after all.

I’m sure there are a number of ways to do this. I had to do it recently on a new project, and I followed Dave Rupert’s lead, who implemented it on ShopTalk’s website to display the localized time for our next live show.

Libraries

Moment.js and Moment Timezone are a pair that can get this done. And if you need to do any other heavier date and time manipulation or relative calculations (e.g. “32 minutes ago”, “12 de Agosto de 2015”), you’ll be in good hands with these libraries.

We’ll also need to detect the time zone itself, and thankfully there is a library for that.

So we’ll be using:

  • jstz.js
  • moment.js
  • moment-timezone.js

Package or link those up however you will.

Step 1: Get the Timezone

Might as well stash it in localStorage after you’ve gotten it. That requires less effort on the browser’s part to retrieve next time.

if (!sessionStorage.getItem('timezone')) {
  var tz = jstz.determine() || 'UTC';
  sessionStorage.setItem('timezone', tz.name());
}
var currTz = sessionStorage.getItem('timezone');

Step 2: Get a Time Value

Moment expects a date/time value (in UTC) like:

2015-08-12T14:30Z

If we’re only interested in the time, we can create the date portion of that string from Moment itself of today’s date (just makes the formatting way easier). The date actually kinda matters since UGHGKGJHGH daylight savings.

var date = moment().format("YYYY-MM-DD");

Then we’ll create the final string, assuming we have a variable with the time we want:

var stamp = date + "T" + theTime + "Z";

And turn it into a Moment object:

var momentTime = moment(stamp);

Step 3: Localize the time

Now we can adjust/localize that time with Moment Timezone:

var tzTime = momentTime.tz(currTz);

And properly format it for display:

var formattedTime = tzTime.format('h:mm A');

Step 4: Use it

Now we can drop it on the page anywhere we want. If you output the time zone as well, you could even replace the time currently output on the page, since even if detecting the time zone fails it will fall back to UTC and output that as the time zone.

output.textContent = "Time in " + currTz + ": " + formattedTime;

Adjusting Times

Sometimes it makes sense (perhaps from a CMS perspective) to ask people to input time in a local time zone. But in order to do the conversion correctly, it makes more sense to have that time in UTC.

Moment itself can help with adjusting times, like:

moment().subtract(4, 'hours');
moment().add(3, 'hours');

Server side languages can help too. For instance PHP can do math on times:

<?php var $sixHoursAgo = strtotime("-6 hours", time()); ?>

It probably makes the most sense to do that with Moment Timezone, because it’s not always an exact formula (again UGHADKGHK daylight savings).

Demo

In this demo we use an HTML5 time input and adjust it on the fly to a localized time.

 

 

Last Words

The dependencies we used here are not insignificant! It appears there are native JavaScript methods (e.g. getTimezoneOffset()) that have pretty good support that could be used to similar effect.

 


How the Web Works

How the Web Works

How the Web works provides a simplified view of what happens when you view a webpage in a web browser on your computer or phone.

This theory is not essential to writing web code in the short term, but before long you’ll really start to benefit from understanding what’s happening in the background.

Clients and servers

Computers connected to the Web are called clients and servers. A simplified diagram of how they interact might look like this:

  • Clients are the typical Web user’s Internet-connected devices (for example, your computer connected to your Wi-Fi, or your phone connected to your mobile network) and Web-accessing software available on those devices (usually a web browser like Firefox or Chrome).
  • Servers are computers that store webpages, sites, or apps. When a client device wants to access a webpage, a copy of the webpage is downloaded from the server onto the client machine to be displayed in the user’s web browser.

The other parts of the toolbox

The client and server we’ve described above don’t tell the whole story. There are many other parts involved, and we’ll describe them below.

For now, let’s imagine that the Web is a road. On one end of the road is the client, which is like your house. On the other end of the road is the server, which is a shop you want to buy something from.

In addition to the client and the server, we also need to say hello to:

  • Your Internet connection: Allows you to send and receive data on the Web. It’s basically like the street between your house and the shop.
  • TCP/IP: Transmission Control Protocol and Internet Protocol are communication protocols that define how data should travel across the Web. This is like the transport mechanisms that let you to place an order, go to the shop, and buy your goods. In our example, this is like a car or a bike (or your own two feet).
  • DNS: Domain Name System Servers are like an address book for websites. When you type a web address in your browser, the browser looks at the DNS before retrieving the website. The browser needs to find out which server the website lives on, so it can send HTTP messages to the right place (see below). This is like looking up the address of the shop so you can access it.
  • HTTP: Hypertext Transfer Protocol is an application protocol that defines a language for clients and servers to speak to each other. This is like the language you use to order your goods.
  • Component files: A website is made up of many different files, which are like the different parts of the goods you buy from the shop. These files come in two main types:
    • Code files: Websites are built primarily from HTML, CSS, and JavaScript, though you’ll meet other technologies a bit later.
    • Assets: This is a collective name for all the other stuff that makes up a website, such as images, music, video, Word documents, and PDFs.

So what happens, exactly?

When you type a web address into your browser (for our analogy that’s like walking to the shop):

  1. The browser goes to the DNS server and finds the real address of the server that the website lives on (you find the address of the shop).
  2. The browser sends an HTTP request message to the server asking it to send a copy of the website to the client (you go to the shop and order your goods). This message, and all other data sent between the client and the server, is sent across your internet connection using TCP/IP.
  3. Provided the server approves the client’s request, the server sends the client a “200 OK” message, which means “Of course you can look at that website! Here it is”, and then starts sending the website’s files to the browser as a series of small chunks called data packets (the shop gives you your goods, and you bring them back to your house).
  4. The browser assembles the small chunks into a complete website and displays it to you (the goods arrive at your door — new stuff, awesome!).

DNS explained

Real web addresses aren’t the nice, memorable strings you type into your address bar to find your favorite websites. They are strings of numbers, like this: 63.245.217.105.

This is called an IP address, and it represents a unique location on the Web. However, it’s not very easy to remember, is it? That’s why Domain Name Servers were invented. These are special servers that match up a web address you type into your browser (like “mozilla.org”) to the website’s real (IP) address.

Websites can be reached directly via their IP addresses. Try going to the Mozilla website by typing63.245.217.105 into the address bar on a new browser tab.

A domain name is just another form of an IP address

Packets explained

Earlier we used the term “packets” to describe the format in which the data is sent from server to client. What do we mean here? Basically, when data is sent across the Web, it is sent as thousands of small chunks, so that many different web users can download the same website at the same time. If web sites were sent as single big chunks, only one user could download one at a time, which obviously would make the Web very inefficient and not much fun to use.


10 Best CSS Trends 2019

10 Best CSS Trends 2019

As time goes on, web design is getting more innovative. Rather than just displaying information, websites are works of art, featuring complex animations, unique layouts, and micro-interactions. So many of these things are possible through CSS. CSS gives style to normal, boring web pages, and enables everything that makes websites enjoyable to interact with. 2019 brings with it plenty of new horizons for web design, and these are the 10 best CSS trends that will define the year.

1. Mobile First

Of all the CSS trends, the most current and continuing to grow CSS “sentiment” is towards Mobile First. Historically, web designers have developed web applications for computers first, and then added responsive web design to make sure the web looks good when viewed on a tablet or a phone. This CSS trend is shifting towards designing for mobiles first, and then add responsive design to make a site work on desktops and laptops.

50/50 is an easy way to achieve web design for responsive webs. With 50/50 design, the screen can show two pages on large screens and one page on narrow screens.

2. Cards

Most typical cards are rectangles with an image and some text. Cards have become a common structure for organizing headlines, images, and text on an equal plane. Cards can be small or large, with or without pictures, and with or without shadows. One of the most notable CSS trends and ubiquitous examples is Google Feed cards.

3. CSS Grid

CSS Grid Generator

Take a Look: CSS Grid Generator

The prevailing standard for grid-based layouts has been Flexbox. In fact, at its height at the end of 2018, nearly 83% of page loads on Chrome used Flexbox. But a new contender has entered the ring.

That new contender is Grid. Still young and only seeing use on about 2.25% of page loads, it has still skyrocketed in popularity, only representing 0.25% of page loads at the start of 2018.

Grid is being hailed as better than Flexbox. Flexbox gives you control of vertical or horizontal alignment, but not both at once. Grid, on the other hand, does.

CSS experts attribute the lack of popularity to the fact that most major websites are not using it. After all, that data above is based on page views, not the raw number of pages that use Grid. It was only fairly recently that major sites adopted Flexbox, so it makes sense that they don’t want to make the switch just yet.

2019 will definitely see the growth of Grid, however, because it unlocks a degree of creative freedom that other options do not offer.

4. CSS Writing Mode

Example of CSS Writing Mode

Not all languages are written and read from left to right. For languages that go in other directions, you can use the writing-mode CSS property.

Flow text from top to bottom or from right to left and adjust the horizontal and vertical values. You can even display text sideways vertically, rotate the text for certain designs, and mix scripts.

5. Mobile Animations

Animations as a tool for engagement are increasingly popular. Websites will start to use more and more animated loading icons, page loads with limited design, etc. to keep the user’s attention.

An example of this from a popular website is YouTube. Open the YouTube mobile app and scroll through the videos. If you stop for a second, the video will autoplay with the sound off and show captions.

Animations are also used as indicators for an action or a task. Animated buttons and lists are becoming common too. You read all about using CSS animations from Mozilla.

6. Popular Frameworks (Bulma, Tailwind, Bootstrap 4, etc.)

Foundation CSS Framework

CSS frameworks have been around for a while, but they’ve only been growing in popularity in recent years. If you need a primer on what a framework is, read this.

Awwwards defines a framework as:

“A framework is a standardized set of concepts, practices and criteria for dealing with a common type of problem, which can be used as a reference to help us approach and resolve new problems of a similar nature.”

As we move to a more mobile web, frameworks are adjusting to compensate. Styling and design are changing, animations and action are becoming more common, and a focus on simplicity and end user experience are more important than ever!

In 2019, many well designed frameworks are taking the lead and helping developers and designers to ship faster than ever. A few of the most notable frameworks being used around the web in 2019 are:

  • Foundation – Responsive, mobile-first framework and used as enterprise solution;
  • Bootstrap 4 – Bootstrap is one of the biggest CSS frameworks used worldwide, version 4 comes with new features for color schemes and utility classes;
  • Materialize – Popular framework focused on material design styles;

Read more about the top CSS frameworks 2019 on Scotch.io.

7. Single Pages, Experimental Navigations

Carrd single page website builder.

With websites becoming almost as synonymous as having your own profile on social networks, more users are turning to simpler solutions and single page options to send traffic out to other locations.

Common examples include:

  • Linktree – Simple page with links to your socials, products, etc.;
  • Carrd – Simple, free, fully responsive one-page sites for pretty much anything;
  • About.me – More professional focused portfolio site, similar to LinkedIn but with room for creativity;
  • Instapage – Top landing page builder for businesses and startups;

These single page websites are being taken further with the creative use of CSS and styling to enhance the experience. The Next Web highlighted ‘large and experimental navigations’ as one of their ‘10 exciting web design trends you can’t hide from in 2019’. So why are people moving to these interesting layouts?

Because of action. With the focused large buttons and navigation, users immediately click to the desired location. Whether that be a shop, informational page with hours/details, or just a new video/song.

More and more websites are simply set up as directing points for companies, individuals, or groups to send traffic to and then distribute out. Musicians use Linktree and other services to share their new songs on all streaming platforms, and get a cut of the affiliate revenue in the meantime.

8. Variable Fonts

Google's 'Introduction to variable fonts on the web'.

Highlighted by Carrie Cousins for Designmodo’s ‘Top 17 Web Design and UI Trends 2019’, variable fonts are defined as “a collection of master styles, with one central ‘default’ master (usually the Regular font style) and multiple registered “axes” which tie the central master to the other masters. For example, the Weight axis might connect a Light style master to the default style and through to the Bold style master. The individual styles that can be located along this axis are called “instances”.

What this means is that fonts are more responsive and seamless across devices and platforms. You can scale the width, sizing, and other aspects of the font more easily without jumping from font weight to font weight or switching fonts entirely.

Check out an example of the variable typeface ‘Amstelvar’ on GitHub. Also read the full analysis on variable fonts and how they will change the web from Google.

9. Scroll Snapping

'Practical CSS Scroll Snapping' from CSS Tricks.

Scroll snapping is one of the relatively new CSS trends, and is a technique used for snapping users to certain scroll points. Rather than a fluid motion down the page or left to right, you can have the page scroll in increments. Popular uses of this are for swiping through products or details on a page, scrolling through a book/reading experience, and sliding down a page with incremental blocks of information.

CSS Tricks features a great guide on Practical CSS Scroll Snapping.

The guide features information on browser support, best practices, and the properties you should use to ensure your scroll snapping works as intended.

Want to see how scroll snapping works? Check out these examples on Webkit.

10. Full Screen Input

Last but not least of the CSS trends is the use of full screen inputs. More and more sites are using full screen for inputs like signups and logins, instead of using only a small part of the page. Full screen often uses a screen overlay or modal instead of redirecting to a new page.

If you enjoyed this article regarding the best CSS trends 2019 and want even more CSS info check out our other CSS Guides.


Understanding Proxy Browsers

Understanding Proxy Browsers

I did a bunch of research on proxy-browsers for a few projects I worked on. Rather than sitting on it all, I figured I’d write a post sharing what I learned in case it’s helpful to anyone else. This post looks at the general architecture of proxy browsers with a performance focus.

In the original story of the Wizard of Oz, the Emerald City isn’t actually green nor made entirely of emeralds. All of that came later. In the original story, before entering the city each person had to put on a pair of glasses. These glasses, they were told, would protect them from the bright glow of all the emeralds that would surely damage their sight. These glasses were attached and never removed. You wore them while eating, while going to the bathroom, while walking outside—you wore them everywhere and all the time.

This was all a ruse. The glow of the city wouldn’t damage anybody’s sight because there was no glow. That all came from the glasses which just happened to be tinted green. Through the lens of those glasses, everything glowed. The lens through which those people viewed their world shaped their perception of it.

I’d venture to say that most developers and designers are not big fans of proxy browsers—assuming they pay attention to them at all. They don’t behave in ways a typical browser does, which leads to frustration as we see our carefully created sites fall apart for seemingly no reason at all. And frankly, most of us don’t really need to use them on a day-to-day basis. Through the lens we view the web, proxy browsers are merely troublesome relics of a time before the idea of a “smartphone” was anything other than a pipedream.

But our view of the web is not the only view of the web. People all over the world face challenges getting online—everything from the cost of data and poor connectivity to religious and political obstacles. In these environments proxy browsers are far from troublesome; they are essential.

So while most of us building for the web have never used a proxy browser (outside of the quick spot check in Opera Mini, perhaps), they remain incredibly popular globally. Opera Mini, the most popular of all proxy browsers, boasts more than 250 million users. UC, another popular proxy browser, boasts 100 million daily active users and is the most popular mobile browser in India, China and Indonesia.

These browsers perform optimizations and transcoding that can provide significant improvements. Several proxy browsers claim up to 90% data savings when compared to a typical browser. That’s the difference between a 2MB site and a 200kb site—nothing to sneeze at.

To understand how they accomplish this—and why they behave the way they do—we first need to revisit what we know about how browsers work.

Typical Browser Architecture

A typical modern browser goes through a series of steps to go from the URL you enter in your address bar to the page you ultimately see on your screen. It must:

  1. Resolve the DNS
  2. Establish TCP connection(s) to the server(s)
  3. Request all the resources on a page
  4. Construct a DOM and CSSOM
  5. Build a render tree
  6. Perform layout
  7. Decode images
  8. Paint to the screen

That’s a very simplified list and some of them can happen in parallel, but it’s a good enough representation for the purpose of highlighting how proxy browser architecture differs.

We can break these steps out into two general buckets. Steps 1-3 are all network constrained. How quickly they happen, and the cost, depends mostly on the characteristics of the network: the bandwidth, latency, cost of data, etc.

Steps 4-8 are device constrained. How quickly these steps happen depends primarily on the characteristics of the device and browser: the processor, memory, etc.

Proxy browsers intercede on behalf of the user in an attempt to reduce the impact of one, or both, of these buckets. You can broadly classify them into two categories: browsers with proxy services, and remote browsers.

Browsers with proxy services

The first category of proxy browsers are really just your plain-old, everyday browser that happens to offer a proxy service. These browsers alter the typical browser behavior only slightly, and as a result they provide the least benefit for end users as well as—usually—the least noticeable impact on the display and behavior of a web site. (While not really tied to a browser, look at Google’s search transcoding service for an example of how substantially a proxy service could alter the display of a page.)

Instead of requests being routed directly from the client to the web server, they are first routed through some intermediary layer of servers (Google’s servers, UC’s servers, Opera’s servers, etc). This intermediary layer provides the proxy service. It routes the request to the web server on behalf of the client. Upon receipt of the request, it sees if there are any optimizations it can provide (such as minification, image compression, etc) before passing back the potentially altered response to the client.

The browser-specific behavior (steps 4-8) remains the same as the typical browsers you’re used to testing on. All of the optimizations that take place focus primarily on the reducing the impact on the network (1-3).

There are many examples but at the moment of writing some of the more popular options in this category are Google’s Data Compression tool (Flywheel), UC Web’s Cloud Boost, and Opera Turbo.

Remote browsers

Remote browsers push the limits a bit more. They aggressively optimize as much as possible providing a much larger benefit for the end user, but also a lot more trouble for developers. (If that bothers you try to remember that the proxy browsers exist because users need them, not because developers do.) These are the browsers you more typically think of when hearing the term “proxy browser”. With the increase in browsers offering proxy services, I think referring to these as remote browsers can be a helpful way of distinguishing them.

Unlike their more conservative brethren, remote browsers are not content to merely make a few optimizations on the network side of things. They’ve got more ambitious goals.

When a website is requested through a remote browser, the request is routed through an intermediary server first before being forwarded on to the web server. Sounds familiar right? But here’s where remote browsers start to break away from the traditional browser model.

As that request returns to the server, instead of the intermediary server routing it back to the client, it proceeds to request all the subsequent resources needed to display the page as well. It then performs all parsing, rendering, layout and paint on the intermediary server. Finally, when all of that is taken care of, it sends back some sort of snapshot of that page to the client. This snapshot does not consist of HTML, CSS and JavaScript—it’s a proprietary format determined by whatever the browser happens to be.

That’s why calling them “remote browsers” makes so much sense. The browser as we know it is really contained on the server. The application on the phone or tablet is nothing more than a thin-client that is capable of serving up some proprietary format. It just so happens that when it serves that format up, it looks like a web page.

The most important thing to remember for remote browsers is that because all they are doing is displaying a snapshot of a page, anything that might change the display of that page requires a trip back to the server so an updated snapshot can be generated. We’ll discuss that in more detail in a later post as the implications are huge and the source of most proxy browser induced headaches.

There are many options, but Opera Mini, UC Mini and Puffin are some of the more popular.

Reference: timkadlec.com