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).

Advertisements
10 Best CSS Trends for 2019

10 Best CSS Trends for 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 for 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 for 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 for 2019 and want even more CSS info check out our other CSS Guides.

References: Mozilla, Awwwards, 1stWebdesigner, TheNextWeb, DesignModo, CSS-Tricks

How to Create The Apple Watch Breathe App Animation with CSS

How to Create The Apple Watch Breathe App Animation with CSS

The Apple Watch comes with a stock app called Breathe that reminds you to… breathe. There’s actually more to it than that, it’s a self wellness app of sorts, that reminds you to take a brief moment out of your stressful day and focus on your breathing to encourage relaxation. Additionally, the app has a minimalistic interface with a nice animation.

I thought it would be fun (and relaxing) to recreate the design, particularly in vanilla CSS. Here’s how far I got, which feels pretty close.

 

Making the circles

First things first, we need a set of circles that make up that flower looking design. The app itself adds a circle to the layout for each minute that is added to the timer, but we’re going to stick with a static set of six for this demo. It feels like we could get tricky by using ::before and ::after to reduce the HTML markup, but we can keep it simple.

<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>

We’re going to make the full size of each circle 125px which is an arbitrary number. The important thing is that the default state of the circles should be all of them stacked on top of one another. We can use absolute positioning to do that.

.circle {
  border-radius: 50%;
  height: 125px;
  position: absolute;
  transform: translate(0, 0);
  width: 125px;
}

Note that we’re using the translate function of the transform property to center everything. I had originally tried using basic top, right, bottom, left properties but found later that animating translate is much smoother. I also originally thought that positioning the circles in the full expanded state would be the best place to start, but also found that the animations were cumbersome to create that way because it required resetting each one to center. Lessons learned!

If we were to stop here, there would be nothing on the screen and that’s because we have not set a background color. We’ll get to the nice fancy colors used in the app in a bit, but it might be helpful to add a white background for now with a hint of opacity to help see what’s happening as we work.

 

We need a container!

You may have noticed that our circles are nicely stacked, but nowhere near the actual center of the viewport. We’re going to need to wrap these bad boys in a parent element that we can use to position the entire bunch. Plus, that container will serve as the element that pulses and rotates the entire set later. That was another lesson I had to learn the hard way because I stubbornly did not want the extra markup of a container and thought I could work around it.

We’re calling the container .watch-face here and setting it to the same width and height as a single circle.

<div class="watch-face">
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
</div>

Now, we can add a little flex to the body element to center everything up.

body {
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

 

Next up, animate the circles

At this point, I was eager to see the circles positioned in that neat floral, overlapping arrangement. I knew that it would be difficult to animate the exact position of each circle without seeing them positioned first, so I overrode the transform property in each circle to see where they’d land.

We could set up a class for each circle, but using :nth-child seems easier.

.circle:nth-child(1) {
  transform: translate(-35px, -50px);
}

/* Skipping 2-5 for brevity... */

.circle:nth-child(6) {
  transform: translate(35px, 50px);
}

It took me a few swings and misses to find coordinates that worked. It ultimately depends on the size of the circles and it may take some finessing.

 

Armed with the coordinates, we can register the animations. I removed the transform coordinates that were applied to each :nth-child and moved them into keyframes:

@keyframes circle-1 {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(-35px, -50px);
  }
}

/* And so on... */

I have to admit that the way I went about it feels super clunky because each circle has it’s own animation. It would be slicker to have one animation that can rule them all to push and re-center the circles, but maybe someone else reading has an idea and can share it in the comments.

Now we can apply those animations to each :nth-child in place of transform:

.circle:nth-child(1) {
  animation: circle-1 4s ease alternate infinite;
}

/* And so on... */

Note that we set the animation-timing-function to ease because that feels smooth…at least to me! We also set the animation-direction to alternate so it plays back and forth and set the animation-iteration-count to inifinite so it stays running.

 

Color, color, color!

Oh yeah, let’s paint this in! From what I can tell, there are really only two colors in the design and the opacity is what makes it feel like more of a spectrum.

The circles on the left are a greenish color and the ones on the right are sorta blue. We can select the odd-numbered circles to apply the green and the even-numbered ones to apply the blue.

.circle:nth-child(odd) {
  background: #61bea2;
}

.circle:nth-child(even) {
  background: #529ca0;
}

Oh, and don’t forget to remove the white background from the .circle element. It won’t hurt anything, but it’s nice to clean up after ourselves. I admittedly forgot to do this on the first go.

 

It’s also at this point that others in the comments have suggested that replacing opacityfor mix-blend-mode with a value of screen makes for a nicer way to blend the colors of the circles. I’ve since updated the demos and the code.

Pulse and rotate

Remember that pesky .watch-face container we created? Well, we can animate it to pulse the circles in and out while rotating the entire bunch.

I had totally forgotten that transform functions can be chained together. That makes things a little cleaner because it allows us to apply scale() and rotate() on the same line.

@keyframes pulse {
  0% {
    transform: scale(.15) rotate(180deg);
  }
  100% {
    transform: scale(1);
  }
}

…and apply that to the .watch-face element.

.watch-face {
  height: 125px;
  width: 125px;
  animation: pulse 4s cubic-bezier(0.5, 0, 0.5, 1) alternate infinite;
}

Like the circles, we want the animation to run both ways and repeat infinitely. In this case, the scale drops to a super small size as the circles stack on top of each other and the whole thing rotates halfway on the way out before returning back on the way in.

I’ll admit that I am not a buff when it comes to finding the right animation-timing-function for the smoothest or exact animations. I played with cubic-bezier and found something I think feels pretty good, but it’s possible that a stock value like ease-in would work just as well.

All together now!

Here’s everything smushed into the same demo.

 

If you’re having a stressful day, even you don’t have an apple watch, you can gaze into the CSS animation you’ve created and lull yourself into tranquility.

Make sure you don’t keep all of this peacefulness to yourself, and pass along your newly discovered knowledge. 

For all things Apple, check out all of our latest Apple related guides.

references: apple, css tricks, codepen, mozilla

CSS Transitions and Animations: Intro Guide

CSS Transitions and Animations: Intro Guide

I’ve noticed in the comments of other posts recently that some readers would like more “tips and tricks” articles, particularly about CSS. So in today’s post, I’ll be providing what I hope is a useful introduction to a bit of CSS “trickery” that can be used to create compelling microinteractions across your website. Specifically, we’ll be learning how to create CSS transitions and animations. We’ll also be talking about when and where you might want to use them.

What Are CSS Transitions and Animations?

The evolution of CSS over the years has lead to some really amazing innovations within the language. In the case of transitions and animations, what previously required a program like Adobe Flash or another coding language altogether (such as Javascript) is now possible with nothing but HTML and CSS.

This kind of language maturity, enabled by better browsers and higher web standards (among other things), has been a huge boon to web designers who double as front end developers. They can now do more with less and the whole process of web design/development has become a bit easier.

Nevertheless, CSS transitions and animations are still considered advanced uses of CSS. A spectrum of coding I try to stay away from in most of my articles since I do not consider myself an “advanced developer”–even in language as accessible as HTML or CSS.

That said though, after reading up on W3Schools and elsewhere I think a sufficiently simple introduction to these concepts is within the grasp of not only myself but a good deal of the WTG readership as well.

To begin, I think we need to have a really good idea of what, exactly, CSS transitions and animations are before jumping into examples and code.

CSS Transitions

A CSS transition allows you to change the property values of an element over a given duration that you set. To create a transition you must first identify which CSS property you want to add an effect to and then specify the duration of the effect. If no duration is set, the transition will not occur.

There are four transition properties:

transition-delay – specifies the delay, in seconds (s), you would like to assign your transition effect.

transition-duration – specifies the duration, in seconds (s) or milliseconds (ms), you would like to assign your transition effect.

transition-property – specifies the name of the CSS property your transition effect is meant for.

transition-timing-function – Specifies the speed curve of the transition effect. Meaning, the type of speed variation you want to select for your transition effect. There is no “fast” or “slow” options. Instead there are speed curve options that go from one speed to another. Such as “ease” which tells your effect to start slow, then go fast, then end slowly.

To create a transition you only need to change one of these properties over the duration you choose. However, it is possible to change more than one property at the same time; resulting in more dramatic transitions.

CSS Animations

Where CSS transitions are all about altering element properties as they move from state to state, CSS animations are dependent on keyframes and animation properties.

keyframes – keyframes are used to define the styles an element will have at various times.

animation properties – animation properties are used to assign @keyframes to a specific element and determine how it is animated.

There are eight animation properties:

animation-delay – specifies a delay for the start of an animation.

animation-direction – specifies whether an animation should play in reverse direction or alternate cycles.

animation-duration – specifies how many seconds or milliseconds an animation takes to complete one cycle.

animation-fill-mode – specifies a style for the element when the animation is not playing. Such as when it is finished or when it has a delay.

animation-iteration-count – specifies the number of times an animation should be played.

animation-name – specifies the name of the @keyframes animation.

animation-play-state – specifies whether the animation is running or paused.

animation-timing-function – specifies the speed curve of the animation.

The examples below will show you how these things are used together in various ways. Once you understand the relationships between them you’ll be able to figure out all kinds of interesting ways to use them.

A Quick Note on Vendor Prefixes

In your personal usage of CSS transitions and animations you will most likely need to use vendor prefixes. In some of the code below you will no doubt notice some vendor prefixes. Many of the source examples do not contain vendor prefixes, so if you want to see what the code looks like without them you can check there; I thought it might be helpful to provide a fuller picture.

For the uninitiated, when I say “vendor prefix” I’m referring to a prefix that needs to be added to your CSS based on the range of browsers you want to support your transitions and animations.

A good resource for identifying the necessary prefixes for each browser is caniuse.com. You can also check out the respective pages for transitions and animations on W3Schools. Or, if you’d like to avoid the mess of prefixes altogether, you can use a tool like Bourbon.io.

CSS Transition Examples

The CSS transition examples below are all transitions I’ve found from various sources that show what’s possible with these relatively new CSS capabilities. I’ve chosen to recreate the examples I found using CodePen so you can easily take a peak at the HTML and CSS required for each example while also seeing it in action
1. Linear

Example via.

2. Spin

Example via.

3. Color

Example via.

4. Square to Circle

Example via.

5. Card

Example via.

CSS Animation Examples

Again, the CSS animation examples below are from various sources around the web. Just as above, the CodePen allows you to see the animation and the required code in one place. You can also follow my source links to get more information (in some cases) on each example.
1. Pulse

Example via.

2. Shake

Example via.

3. Bouncing

Example via.

4. Bounce In

Example via.

5. Linear Bar

Example via.

Potential Use Cases for CSS Transitions & Animations

As I mentioned above, CSS transitions and animations are ideal for creating compelling and delightful microinteractions across your website. A lot of great WordPress themes and plugins come with some of these behaviors in place. A good example being the Divi Builder, which allows you to control transitions and animations within its module controls.

You may however wish to take the basics above and apply them other areas of your site in which a theme or plugin author has not given you easy control over. The following ideas might help you get started.

  • An email opt-in form that makes a delightful entrance and exist; such as bouncing in and folding closed to disappear.
  • A form that shakes when the essential information is not and someone attempt to submit it as finished.
  • Buttons that fold open, bounce, shake, or in some other way respond to hovering and clicking.
  • Preview images that turn over to reveal more information.
  • Subtle background graphics that move, creating depth.
  • Beautiful charts that spring into action as they load.
  • Google Doodle style experiments, logos, and more.
  • Games (for the really ambitious).
  • Ads that you can interact with or that subtly change shape to draw attention.
  • Beautiful product displays that rotate and respond to the mouse.
  • Beautiful stat counters.
  • And whatever else your imagination can think up.

Inspiring Showcases of CSS Transitions and Animations

If you need more visual stimulus than a list of ideas, I’ve take the liberty of compiling a small but impressive showcase of inspiring CSS transitions and animations that I hope will show off the potential illustrated in the rather basic examples I created above.

Logos in Pure CSS

Logos-In-Pure-CSS

Logos in Pure CSS is a great showcase of world famous logos re-created with nothing but CSS. In their current form they use animations and transitions to show how they are made and how they stack up against their traditional counterparts. However, I think it’s important to note that just creating your logo in HTML/CSS opens up a lot of interesting possibilities.

Go to Logos in Pure CSS

CSS A/Z

CSS-A-Z

CSS A/Z is a showcase of HTML/CSS animated sketches; one for each letter of the alphabet. Great stuff and a lot of ideas for sprucing up seemingly insignificant elements on your website.

Go to CSS A/Z

Double Ring

Double-ring

I think Double Ring is a great example of something you could do with a logo to make it more eye catching and interesting.

Go to Double Ring

Navigation Bar

nav-bar

Navigation Bar is an example of just how dynamic and beautiful something as standard as navigation can become when given some advanced CSS love.

Go to Navigation Bar

In Pieces

In-Pieces

In Pieces is a magnificent (and highly complex) use case of CSS animation. It’s an interactive exhibition of the evolution of 30 species of animals. Truly breathtaking and a great indicator of just how powerful a tool CSS can be.

Go to In Pieces

Additional Resources & Tutorials

In your quest to master CSS transitions and animations, there is a good chance that you’ll need or want more detail than I am able to provide in this post. Additionally, someone else’s writing style may be a bette fit for the way you think. That’s why I’ve compiled a short list of other useful resources and tutorials below for you to take advantage of.

In Conclusion

CSS transitions and animations are an extremely useful and versatile set of capabilities. You can do small subtle things or big in-your-face impressive things. But either way, it all starts with mastering the basics and moving on from there.

I hope this post is a welcome change of pace for those who have been requesting more CSS related content. If you have any more thoughts or requests on this post or future posts then please feel free to drop us a line in the comments section below.

references: elegant themes, w3schools, shayhowe, caniuse, bourbon

Data Table with CSS – How to Tame

Data Table with CSS – How to Tame

A data table can be a pain to work with, perhaps comparable to herding cats or taming a lion.  Tons of similar-looking, heavily-nested markup can be viewed as completely inflexible. One of the biggest problems I ever encountered was working on a particular company, whose content was almost exclusively data tables, it involved making tables’ cells line up nicely not only with each other, but also with those cells in other tables on the page.

Example of a data table with css:

The problems

There are a lot of headaches we encounter when building tables, and I imagine most of you reading this article will nod along to every point I make; it will be something that will have annoyed us all at some point or another. What this particular (and very specific) problem boils down to is trying to consistently format, size and align complex data layouts across multiple tables. Imagine a financial report; loads of tables of data with differing numbers of cells and columns that—from a purely aesthetic perspective—need to line up in some neat, coherent fashion. Achieving this is made very difficult by a number of different factors…

Cell widths

Tables lay out their cells—by default—in a rather unusual, almost haphazard way. There seems to be no rhyme or reason behind how and why they are rendered at the widths they are, which leads to columns and cells of differing sizes.

Spanning cells

In order to have cells span several columns (and rows, but that doesn’t pose the same problems), we have to use the colspan attribute. To have a cell spanning two columns we would write <t[h|d] colspan="2">. These are often unmanageable, and it can be confusing to remember what all your colspans should add up to.

Knock-on effects

Resizing one cell in one row can, and usually will, affect the layout of the entire table. This is is because all cells’ boundaries have to line up with the boundaries of the rest of the row and column in which it sits. You can’t just change the width of one cell, you have to change them all. This means that, for example, spanning one cell across xcolumns might mean having to update a whole load more colspans elsewhere in thetable.

Tables next to tables

The above problems are further compounded when you begin laying out multiple different tables on any given page. In Sky Bet world, this was pretty much every page. One table’s rendered layout might be vastly different to the tables above and/or below it, creating an unsightly mess of misaligned columns. You might have a tablewith no colspans above a table with some colspans, above a table with lots of awkward colspans. You might have a table with lots of cells above a table with very few. You might have any combination of amounts of cells and amounts of colspans. It all gets very hairy, very quickly.

Solution

I’ve come up with what I feel is a solid, very pragmatic solution.

There are two parts to solving this problem. Firstly we need to standardize the number of cells in every table, and then we need to force these cells to all be the same width. Think of this as a grid system for tables.

24 cells

Think about page layouts that adhere to a grid system; you might have a 24 column grid, but your page might only have two main columns which span, say, 16 and eight columns respectively. You can’t see the 24 columns, but they’re there. You might then have a large footer broken into three columns of eight (again, adding up to 24).

We need to apply this model to tables; we shall give all tables 24 columns, and then use a generous amount of colspans to knock our cells through into each other, into more useful layouts. Now every table we build will be based on a 24 column grid which will, firstly, make everything more consistent, and, secondly, it will make our maths much simpler. We just need to make sure every row’s colspan values add up to 24 every time.

This does mean that every cell in the table now has to carry a colspan, but as I said, this solution is a pragmatic one.

The reason we pick 24 is because it can take halves, thirds, quarters, sixths, eighths and twelfths; we can make a lot of layouts if we have 24 columns to play with.

Now, we would write this snippet:

...
    <th>Column one</th>
    <th>Column two</th>
    <th>Column three</th>
...

as:

...
    <th colspan="8">Column one</th>
    <th colspan="8">Column two</th>
    <th colspan="8">Column three</th>
...

For all this is more markup, it does mean we can begin to standardise our tables’ layouts so that multiple tables on the same page can share a lowest common multiple and are now able to be aligned to one another.

The short version of this section is basically: we are setting up a grid system for ourtables.

Equal width columns

It’s all well and good that all our tables have the same number of columns, but that doesn’t escape the fact that browsers will still render every table differently, and that the size of these cells will always vary. There’s no point having a 24 column table-grid-system if each column is a different width. Thankfully, this is the easiest part of the puzzle to solve and, probably, the most interesting part of this article: table-layout: fixed;.

Now it’s time to tame a data table with css.

There is a little known, and even less used, CSS property called table-layout. table-layout basically tells a browser how to render the columns in a table, and is, by default, set to auto. auto means that the browser will automatically render the cells in a table based on their width, which leads to the differently and inconsistently sized columns.

Interestingly, table-layout: fixed; is the backbone of my pure CSS, equal-width tabs.

Setting table-layout to fixed however, tells the browser to render every cell the same width as each other. Equally-sized table cells right out of the box!

Combining the two

By giving our tables a common grid system of 24 columns, and ensuring these columns are all of equal width, we can begin throwing together all manner of layouts.

I would propose that you opt into the table-grid-system via a simple helper class, perhaps .table-grid:

.table-grid {
    table-layout: fixed;
}

Every time we want to build a table to a fixed and consistent layout, we simply invoke the grid and lay it out to that.

Hopefully now you’ve gained an edge and can control a data table with css on your project(s).