Position Sticky Pure CSS: Scroll To Top Then Fixed

Position Sticky Pure CSS: Scroll To Top Then Fixed

Position Sticky Pure CSS – Scroll To Top Then Fixed

For a time “dynamic fixed” elements were the hot web design feature: scroll a site and everything moved as expected, but when a particular element (often a menu bar, sometimes an advertisement) reached the top of the page it would fix itself in place, while the rest of the document continued to scroll underneath it. Scroll back, and the element would reattach itself to the document.

This behaviour – a dynamic hybrid between the standard position: static and position: fixed – was often added to a page with JQuery, via one of a hundred different plugins. Like many popular features, it was eventually adopted into an official specification, meaning that the effect could be achieved with native CSS, with no frameworks, scripts, or other dependencies… but in this case, the adoption process was (and continues to be) somewhat troubled.

How Things Were Meant to Be

The behavior was codified as a new CSS value: position: sticky. This, combined with a clever use of top (in the context of sticky, the distance from the top of the body at which the element will “stick” when scrolled; alternatives are left, bottom and right for scrolling in those directions) was intended to cover the range of popular use cases. The syntax, then, should be pretty simple:

#stickytest {
position: sticky;
top: 0px;
}

Applied to something like an image, the markup would be:

<img src="geckofoot.jpg" alt id="stickytest"> <p>Lorem ipsum…

If you test that code on a page with appropriate markup and content in a recent version of Firefox, it will work just fine. Moving to other browsers reveals “sticky’s” awkward position:

  1. Safari 6.1+ (on both desktop and mobile) support sticky with a vendor prefix. Somewhat unusually, the prefix is applied to the value, not the property, since it’s the former that’s new.
  2. There’s an added catch: in Safari sticky only works with elements that are display: block, so the CSS for this sticky image example becomes:
#stickytest {
display: block;
position: -webkit-sticky; position: sticky;
top: 0px;
}

In addition:

  • Placing the sticky element inside a parent that has overflow: hidden applied to it will cause the sticky behaviour to fail.
  • Officially, sticky should also work with display: table, including table cells, as it’s very useful for navigating long rows of table data while keeping column headers in view. Unfortunately, browser implementation of this feature has been lacking so far.

Chrome Travails

You’ll probably find web pages that insist Chrome has support for position: sticky as an experimental option, and that was true… until the option was removed entirely in Chrome 37. The Google development team felt that keeping position: sticky was too much of a challenge in their quest to improve composition and rendering speed in the browser, so it has been placed to one side. That means we must fallback to using a polyfill to recreate the behaviour in Chrome and Internet Explorer (which has never supported the new value).

Fortunately, there are a number of options for this: the Filament Group has a JQuery solution, along with many others; my personal favorite is Oleg Korsunsky’s stickyfill, which has the option of working with or without JQuery.

The example on the StickyFill page adds the sticky behaviour as a class, but it’s more likely to affect only one element, making an id a more logical selector. In the case of this demo, after inserting the script at the bottom of the page, I’d add:

Stickyfill.add(document.getElementById('stickytest'));

Note that top, left, bottom and right for the element is measured from the body. This will include any margin already in place on the body element.

Keep It Simple

As with all new features, position: sticky has the potential for misuse. To avoid UI disasters, I would recommend the following:

  • In theory, position: sticky can be used to fix elements inside any scrolling container, as shown in the example at the top of this page. Please don’t use sticky more than once per page: we don’t need multiple content boxes acting like clogged drains. (In addition, all the polyfills available for position: fixed fail in providing this feature; the demo for this page only works because it is inside an iframe).
  • Be very careful using position: sticky at mobile screen sizes: anything that is stuck immediately takes up screen real estate, reducing the room for your content. Make sure you’re making an element sticky because it’s required or extremely helpful to do so, not because it “looks cool”. Remember that it’s easy for users to flick-scroll to the top or bottom of most pages; don’t get in the way of that behaviour.

To provide a reasonable use of sticky elements, write a @media query that countersposition: sticky at smaller screen sizes:

@media all and (max-width: 600px) {
#stickytest {
position: static !important;
}
}

This returns the element to normal flow in the document if the viewport is 600 pixels wide or less. You’ll need to write a similar rule in JavaScript with matchMedia if you’re using a polyfill. Re-writing and adding to the script above:

var sticky = document.getElementById('stickytest');
var screencheck = window.matchMedia("(max-width: 600px)");
Stickyfill.add(sticky);
if (screencheck.matches) {
Stickyfill.remove(sticky);
}
  • As a rule, “stuck” elements should be the new cutting-off point for content. Don’t “stick” an element in the middle of a block, as having scrolling text appear both aboveand below a fixed element is very distracting, and makes the text difficult to read.
  • Similarly, try to avoid sticking elements that cut off part of a text block, forcing the user to scroll in a decreased amount of space to read a full line.
  • Ensure that the fixed element does not occupy more than the minimum expected height of the viewport. If it is taller than its container when it is “stuck”, users will never be able to see all of its content; nor are they likely to be able to read any of the other content on the page.
  • Further to this, you might want to indicate that content is truly disappearing under the stuck element: a partial transparency effect when the element is in it’s “stuck” position, such as my “frosted glass” effect, can provide a useful visual cue.

In principle, as series of elements could be provided with the same position: stickyvalue, effectively replacing each other at the chosen point on the screen as the page scrolls. While this can be effective, it’s also potentially very confusing to users, and should be employed carefully.

Unfortunately there’s no “stuck” event in JavaScript yet to report when an element has entered its fixed position; right now, you have to test for that independently. (Some polyfills add a class to stuck elements to make up for this lack).

css position sticky
css sticky
position sticky css
css sticky footer
sticky footer css
css sticky header
sticky header css
css sticky navbar
sticky position css
sticky css
sticky navbar css
sticky sidebar css
sticky menu css
sticky nav css
css sticky menu
css sticky position
css position sticky not working
sticky navbar css only
css sticky nav
css sticky table header
css sticky header on scroll
sticky note css
css sticky sidebar
css grid sticky footer
css sticky not working
sticky div css
sticky navigation css
sticky header on scroll css
sticky headers css
sticky button css
css position: sticky
position: sticky css
sticky element css
css position;sticky
css position sticky move
set right position on sticky css
css position webkit sticky invalid
css position absolute sticky
position sticky css myanimelist
css position sticky not sticking
css’s position: sticky
position sticky in css
css -webkit position sticky
position sticky css selector
firefox css position sticky
css position sticky top 0 does not work
css multiple position sticky
css position sticky medium.com
css position sticky right side
add stop position for sticky element css
position sticky view css
css position sticky browser support
position attribute css sticky
position sticky grid css
position sticky css property
css position sticky still scrolls not fixed
css position sticky body height 100
css position sticky for ie 11
css emulate position sticky
safari css position sticky
css position sticky and float
css position sticky unset initial
position sticky top css
make position absolute then sticky css
keithclark css position sticky
css position sticky internet explorer
position sticky css chrome
webkit prefix position sticky css
how to use sticky position css
css position sticky webkit
css position sticky mobile menu not scrolling
position sticky css left
css position sticky for button
firefox css position sticky issue
css position sticky w3schools
css set sticky start position
css sticky x position
css position absolute and sticky
position sticky within css grid
adjust position of sticky on page css
css overflow scroll position sticky
css position sticky mobile menu scroll
css sticky position right
how to set position of text to sticky css
css grid position sticky
css position sticky flexbox
css menu position sticky
position sticky not working css
css position:sticky auto height
css position sticky ie 11
position sticky css not working in ie11
position sticky css not working
css position sticky reverse
css position sticky scroll jump
position sticky css footer
css position sticky compatibility
css position sticky on varying height content
css position sticky top and bottom
css sticky position example
why does my sticky position css
css use sticky position in a style
css position sticky list-item
html css position sticky logo
how to make sticky position to the right css
css position webkit sticky
css div position sticky to another div
css position sticky support
position:sticky css
browser prefix for position sticky css
css position sticky thead tr
css position sticky how to hide elementh benith top menu
css check if sticky position is supported
css position sticky jumping
css position sticky dans un div
css check position sticky
css position sticky from default position
css sticky appear at scroll position
html css position sticky
css position sticky mdn
css using position sticky example
cant get css position sticky to work.
css position sticky caniuse
css position:sticky
safari css position webkit sticky
css sticky position not working chrome
sticky position change css
css position sticky example
sticky position css not working
using position sticky css
css sticky position text displays content underneath
how to position sticky with css
position sticky css compatibility
position sticky header css
css position sticky overflow
css position sticky bottom of screen
css position sticky with elements created dynamically
css position sticky polyfill
sticky bottom section css position
css position sticky header
css remove position sticky when scrolled past
css position fixed vs sticky
how position sticky css
what is position: sticky css
position: sticky css how to
css position fixed sticky
css position relative and sticky
position sticky css w3
position sticky css tricks
how to do css position sticky
css position sticky bottom
position sticky bottom css
html css position sticky not working
position sticky css bottom of screen
internet explorer sticky css position
css html sticky position
css position sticky tr
test support for css position sticky
revolution slider css position sticky
position sticky css support
position sticky css browser compatibility
css position sticky target when bottom
how to use position sticky css
css position sticky sidebar
browser css position sticky
position sticky css w3schools
absolute and sticky position css
css sticky position samples
css position sticky right
css using position sticky
html css position sticky positioning it right
css position sticky spec
css sticky position shim
css position sticky scroll
position sticky css browser compatability
css position emulate sticky
css sticky position not working
css prevent stop position sticky
css position sticky from computed position
css position sticky sideba not working
css position sticky botttom
css remove position sticky when next item sticks
css position sticky not working in chrome
what is sticky position in css
css position sticky does not work
css position sticky height
css position sticky javascript
css sticky footer position absolute
css position sticky microsoft edge
position sticky css bottom
css position sticky ie
css position sticky safari
css position sticky effect
position sticky css ie11
sticky position (bar) with css or jquery
jquery css position sticky
css position sticky jquery
css table position sticky
css position sticky js
position sticky with css grid
css position sticky z-index
css position sticky vs fixed
position sticky css polyfill
position sticky css example
position sticky css ie
sticky footer css position fixed
css position sticky table header
position sticky css mdn
css position sticky bottom 0
css position sticky jsfiddle
css position sticky horizontal scroll
css position sticky footer
css position sticky not work
css position sticky viewport
position sticky css grid
css position sticky overflow scroll

css scroll to top
scroll to top css
scroll to top of page css
scroll to top css only
scroll to top speed css
css scroll can’t scroll to top
css scroll to top not working in firefox
css mobile view scroll to top
button to scroll to top of page css
css onclick scroll to top
css smooth scroll to top
css overflow scroll to top
scroll to top code with jquery and css
css auto scroll to top
css scroll to top not working in ie
css scroll to top button
scroll to top using css
css mobile scroll doesn’t scroll to top, or bottom fast
css click link scroll to top
scroll to top of page css only
materialize css scroll to top
css div scroll to top
how to force scroll to top button slower css
css transition scroll to top
smooth scroll to top css
scroll to top element css
css scroll to top then fixed
css checked scroll to top of page
css add scroll to top
scroll to top icon css
change scroll to top divi theme css
css & html scroll to top button
css if item in view scroll to top
add speed to scroll to top of page css
scroll to top css code
pure css scroll to top
scroll to top when link clicked css
click button scroll to top css
css triangle scroll to top
change scroll to top wordpress css
scroll to top button html css generator
css tab scroll to top
html css scroll to top
speed to scroll to top of page css
icon scroll to top of page css
css page scroll to top of page width id
css window scroll to top animated
adding a scroll to top button css only
css to scroll to top
css auto scroll to top of a div
scroll to top button html css
css scroll to top wordpree
scroll to top jquery css tricks
css scroll to top animation
how to force scroll to top button to go slower css
divi scroll to top css
slow scroll to top css
smooth scroll to top css html
scroll to top button css
css javascript smooth scroll to top
css scroll to top wordpress
css scroll to top on refresh
css scroll to top transition
pure css scroll to top button
scroll to top with animation css
scroll to top animation css
scroll to top css tricks
scroll to top css html
scroll to top html css
scroll to top html5 css
css scroll to top of div
scroll to top with css
scroll to top css html5
css js scroll to top
scroll to top css button
css scroll to top link
scroll to top pure css
disappearing scroll to top link with jquery and css
css overflow-y scroll to top
scroll to top button by css
scroll to top css animation
scroll to top transition css
scroll to top button css only

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


Take a Look as This Incredible Art Made with CSS

Take a Look as This Incredible Art Made with CSS

One thing about web design is that no matter how many intricately-defined standards there are, you can never be sure that whatever you create is going to look the same in all browsers. Even the very latest versions of the most popular browsers have different ways of handling assorted web technologies, which can affect the way your site renders; that’s why cross-platform testing is so important, especially if you’re relying on cutting-edge CSS animation.

While inconsistencies between browsers can be infuriating, every now and then they can throw up something utterly delightful, and here’s one fantastic example: the pure CSS art of Diana Smith. She creates beautiful browser-based art inspired by classic paintings, using only hand-written HTML and CSS; her latest creation, Lace (in the style of Flemish and Baroque works) is a stunning piece.

“Image” Varies Greatly in Different Browsers

This portrait looks different depending on the browser you view it in, because it’s not an “image” at all. It’s pure web code that your browser renders into a drawing every time you load the page.

Take a Look as This Incredible Art Made with HTML & CSS

PureCSS Lace is the latest of digital artist Diana Smith’s code portraits inspired by Flemish baroque oil paintings, joining PureCSS Francine from May 2018. Along with a few retro-inspired posters and a woman in neon-glowing profile, the pieces are created from code, instead of embedded .jpg image files that look the same no matter how you view them.

So, you can’t save Lace or Francine—you could screenshot them, but that would ruin what makes them so unique—but you can distort them into some pretty wacky versions of themselves, depending on the browser it’s rendered within.

“Because of the artistic nature of this project I have not concerned myself with cross-browser-compatibility, so the live preview will most likely look laughable in anything other than chrome,” Smith wrote in the GitHub repository where each of her projects and their source code is stored.

Motherboard loaded Lace up in several different browsers. The results were definitely laughable, yet still weirdly artful.

These are all screenshots of PureCSS Lace rendered in different browsers, so they’ll look the same in your browser no matter which you use, while showing off how different browsers transform the work.

Safari, for some reason, renders the lace frills of Lace to the front.

 

safari
 

Things get weirder—and more Cubist—in a version of Opera from 2014.

opera
 

Ironically, Microsoft Edge takes all the edges off.

edge
 

Netscape Navigator looks like it was created in Microsoft Paint—appropriate, as both ruled the 90s.

nav
 

“When you look at this image on different browsers, you’re kind of looking at the history of the internet and what was demanded of it at the time,” Smith told Motherboard.

But experimenting with different browsers also reveals a hint of the future: A ton of browsers these days are running Chromium, Google’s open-source browser code. Whereas Pure CSS Lace might have shown off how every browser is unique in the past, it now looks exactly the same on Chrome, Vivaldi, Brave, and Opera.


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.


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