<![CDATA[Jay George]]> – Blog / Css https://jaygeorge.co.uk/blog Thoughts and tutorials about web design. en https://jaygeorge.co.uk <![CDATA[The Web is Shipping in 2022]]> https://jaygeorge.co.uk/blog/the-web-is-shipping-in-2022 https://jaygeorge.co.uk/blog/the-web-is-shipping-in-2022 ]]> For as long as I can remember, the web has improved year on year at a stable but glacial pace. 2022 is different. It's the culmination of process changes and browsers working together more modularly.

2022 is the first year in memory that not only a single major technology ships, but a whole host of powerful technology. The result feels significant.

You see—the web typically moves slower than the 'app' world. But over the last few years, browser vendors—like Chrome, Safari, and Firefox—have been shipping behind experimental 'flags' that have enabled a more modular and faster approach to pushing out new tech.

What does this mean? These new technologies mean more expressive websites, from “scroll-linked” animation to eloquent magazine-like grids and sub-grid layouts.

This new tech is not only exciting for web developers but also for clients and, well… everyone who uses the web. For the rest of the article, I will be running through upcoming technology releases and translating what they mean into plain English.

Hat tips to Bramus Van Damme and Nicole Sullivan (both on the Google Chrome Developer Relations team).

A 26% More Colourful Web

]]>
Think of the modern, vibrant Picadilly Circus curved display vs the washed-out 80s mess of old. This is how good a P3 website feels.
]]> A specification set to release in 2022 called Colour Functions will allow developers to make websites literally 26% more colourful. Access to these colours mostly means we can make websites look much more rich and attractive.

If you're of a certain age and have ever dealt with a web developer, you might remember years ago web developers needed to design in “web-safe” colours.

At that time most consumer computer monitors could only display 256 colours, so if you designed in a broader range, most users wouldn't see the full spectrum of colours.

Colour Functions are kind of the same thing, except this time it's internet browsers holding things back, not monitors.

At the time of writing, most browsers can only access the "sRGB" (standard Red, Green, Blue) colour space, which is limited to a certain amount of colours.

There's a newer standard, known as the P3 (Protocol 3) colour space, where modern monitors and laptops can access a much richer range of colours.

]]>
The inner triangle here shows colours available to the sRGB colour space. The vibrant colours you see outside this are only available to P3 screens.
]]> P3 colours look stunningly rich compared to standard RGB colours. If you're wondering just how good, you can see P3 colours if you open up this demo in Safari (which at the time of writing is the only browser that supports P3).

If you can see all four spectrums (display-p3, lch, and lab), it means you have a P3-capable browser. If you can also notice a difference between the colours, it means you have a modern screen capable of displaying colours in this expanded spectrum.

Once all browsers support P3, web designs will gradually start looking a lot more vibrant and attractive as web developers start implementing P3 colours in designs.

I'm already looking forward to making my neon-infused black/white/blue website look 26% hotter.

Page Transitions

]]>
Page transitions make websites feel more like ‘apps’
]]> I'll be honest; this probably shouldn't be in here since I doubt it will “officially” ship in 2022. However, it is currently available, fully working, in an experimental version of Chrome. I wouldn't include this lightly, but it's just so relatively huge that I couldn't resist.

What are page transitions? Imagine you're on a hotel-booking app, and you click a thumbnail image of a hotel. In the next moment, information will probably slide across from the right, or maybe the hotel thumbnail will enlarge to fill the screen in one smooth motion.

You've just experienced a “page transition”—moving from one state (or page) to another in a smooth transition.

Page transitions are one of the few things that separate websites and 'apps'—apps providing a significantly smoother experience in this case.

We go from one page to the next on the web in “pop” movements without any kind of soft landing.

Transitions, on the other hand, are not only smoother and more visually appealing, but they also show us where we're going. Think of all the animations on your smartphone; when you flick up from the bottom of a screen on an iPhone, iOS shows you what happened in one smooth movement.

For web developers, native page transitions could bring us one step closer to confidently saying to clients, “you probably don't need an app”.

For what it's worth, an older colleague (sorry, Dean) pointed out that we were here decades ago with Internet Explorer 5.5. That obviously didn't last, but I hope this time is different now that we have better browser standards and collaboration between browser vendors.

Scroll-linked Animations

]]>
With scroll-linked animations you can smoothly animate anyting you want based on the user's scroll position
]]> Animating based on a user's scroll position is nothing new on the web.

Just about every client meeting I've had in the last few years can't end until a client smiles knowingly and asks for "parallax" effects.

However, implementing anything scroll-related has always been a bit hamfisted. You'll need to use some sort of script plugin to continually track where the user is on a page. The browser always struggles a little with this kind of stuff. Until now! (or the near-future, at least).

On the horizon is a “native” implementation of scroll-linked animation. “Native” means that the browser has it baked in so that you don't need to load a plugin.

Don't be fooled—this is not just developer convenience. Anything “Native” (baked into the browser) means performance will be significantly better and programming significantly simpler, leading to a much smoother and delightful implementation.

Systems and Components / not Pages

]]>
Historically we've designed websites like _pages_ rather than what they really are: a collection of interlocking and contextual patterns (like Lego). This is about to change with the introduction of Container Queries.
]]> I remember the vast mental shift that Responsive Web Design brought in the 2010s.

If you don't know what I'm talking about, Responsive Web Design was both a mental and technology shift to designing websites that worked on all sorts of different sized devices.

In the simpler days of web development, you'd just design a fixed-width page. With the advent of Responsive Web Design, we could suddenly query the device width. Developers started designing flexible layouts that could adjust to mobile phones, tablets, and various screen sizes.

Intrinsic Web Design

The web will always be an inherently flexible medium. Your website can be literally accessed by thousands of different device types with wildly different capabilities. Someone could access your site on anything from a computer at CERN, to a 2008 Blackberry, to a high-specced 2022 MacBook Pro. Layout and design need to be flexible and adjusted accordingly.

So what follows Responsive Web Design? 4 years ago, Jen Simmons gave a talk called Everything You Know About Web Design Just Changed. This was around the time web developers got access to modern layout models—namely CSS Grid and CSS Flexbox—two incredibly powerful layout technologies that enabled all sorts of wonderful Graphic Design-like layouts.

Fast-forward to 2022, and we're about to get something called Container Queries, which are the crowning jewel we've been waiting for in this era of new layout technology.

Container Queries allow web developers to query the surrounding space of the component. Querying contextual space was never previously possible. Instead, you had to query the area of the whole page. As container queries are released, we can design components that adjust based on context.

Jenn Simmons has suggested a new name to mark this paradigm shift: Intrinsic Design—which indicates that we're designing inherent systems rather than pages.

Web developers have been asking for this sort of expression for years to reflect the truly modular nature of designed components, allowing for more robust designs. Imagine brand guidelines for different components, where you can specify how things will look depending on the space available to them? The Responsive Logos project comes to mind.

Grids and Subgrids

]]>
I hope new layout systems encourage more creative, artistic, and unusual designs
]]> A few years ago, we had (CSS) Grid—a layout technology designed to give developers grid-like control over where designed objects were placed. Think of magazine-style layouts where designers place different arbitrary columns to create unusual artistic designs for feature articles. A few years later, we're on the cusp of “Subgrid”—a way for us to nest interesting design components inside a grid layout while still accessing the external grid references. It's a difficult concept to grasp, but the below image might give you a clearer idea.

]]>
This diagram from a [Smashing Magazine article](https://www.smashingmagazine.com/2018/07/css-grid-2/) by Rachel Andrews gives you an idea of how a subgrid can be nested inside its parent
]]> Previously where developers had needed to program complex layouts, they would do so with some sort of hack that may technically work brittlely, requiring extra code to handle edge cases.

Subgrid means developers can create a much more robust design ecosystem, allowing for more complex designs that stand up to the scrutiny of the ever-growing list of different screen sizes and devices.

Further Reading

I've tried to highlight the most visually understandable browser technology changes in this article, without making it too long. Still, the reality is there are far more technical things on the immediate horizon that only developers—including me!—are excited about.

I've listed more new technologies below to give readers an idea of how much is happening in the web browser space. 2022 is probably the best time there's ever been to be involved in web design and development.

For more technical reading including the below, I'd recommend Bramus Van Damme's blog post on CSS in 2022.

  1. Colour Functions

  2. Viewport Units

  3. :has()

  4. Overscroll Behaviour

  5. Accent Color (for form elements)

  6. Media Query Ranges

  7. Nesting

  8. Scoping

  9. Mixins

  10. Houdini

]]>
Thu, 12 May 2022 00:00:00 +0000
<![CDATA[Designing in the Browser as Fast as Humanly Possible]]> https://jaygeorge.co.uk/blog/designing-in-the-browser-as-fast-as-possible https://jaygeorge.co.uk/blog/designing-in-the-browser-as-fast-as-possible Following the previous video, we'll go through how to design in the browser using more shortcuts and workflow hacks, including some automation software – Keyboard Maestro.

General Tips for Designing

  1. Pop your DevTools “out”—this is a personal preference of mine. It isn't easy to get a clear view of your design when pushed to the side and surrounded by code. You can change how DevTools are displayed by going in the top right > click the vertical dots > and selecting a different docking icon.

  2. Use the Ruler tool—this can really help when trying to make sure elements line up.

    1. To enable the ruler tool, go to the Elements pane in DevTools, press shift + ? to access preferences > click the show rulers checkbox.

    2. A little trick I've learned is highlighting an element, so the rulers are displayed, then scroll vertically-only; without moving your mouse. DevTools will continue to draw rulers as you scroll to check elements beyond the viewport are lined up.

  3. Maintain your own base CSS file—I personally keep a core.css file, and a non-core.css file. I know I'll use everything in core and quite a lot of things in non-core. This can help kick-start a project, and design in the browser immediately without any set-up.

Keyboard Shortcuts

A good metaphor for thinking about automation and keyboard shortcuts is using a well-known tool like Photoshop of a Word document. If you use these all day, you'll start to get used to some shortcuts. For example, Photoshop has single-key shortcuts for things like Brush tool (b), pen tool (p), Stamp tool (s), Switch colours (x). Word has things like Bold (b), Underline (u).

If you use these tools all day long, it's difficult to do without shortcuts. I feel the same way when designing in the browser—I want as many shortcuts as I can remember to get my ideas out fast.

Here are some convenient keyboard shortcuts that are baked into DevTools:

  1. Incrementing—whenever you're keyboard is focused in a number field you can use the up/down arrows to increment by 1, and then combine with modifiers like shift to increment by 10, or alt to increment by 0.1. This works slightly differently in the Elements panel vs the Sources panel—the Elements panel being slightly superior since there is also the option to increment by 0.1.

    1. Incidentally, you can also use your scroll wheel to go up and down values, again using the modifier keys to change the way the numbers increment.

  2. Previous/Next edit points—Use alt & - and alt & + to get to where you were editing previously, or most recently. I find this one particularly useful when working with larger CSS files (like my core.css!) where I'm editing variables at the top of the file and need to get to where I was.

  3. Switching between inspecting and editing—you can use cmd + 1-9 to jump between different panels (you can also rearrange panels to whatever order you want by dragging them around).

    1. This is not turned on by default. To enable this, go to the Elements pane in DevTools, press shift + ? to access preferences > click the Enable cmd + 1-9 shortcut to switch panels checkbox.

    2. I use these shortcuts to switch between inspect mode (the Elements panel) and authoring CSS (the Sources panel).

Automating With Keyboard Maestro

There are a few different automation tools around. TextExpander is probably the most famous. I really like Keyboard Maestro (macOS only, unfortunately – apparently the closest thing on Windows is AutoHotkey). Keyboard Maestro is similar to TextExpander, but its feature set is much much larger, and it pretty much lets you automate whatever you can dream up.

Keyboard Maestro is incredibly handy when it comes to speeding up the authoring experience in DevTools, and you can get a free trial from their website if you're not sure. I have macros that deal with different aspects of authoring:

  1. Text expansions that speed up typing property/value pairs, for example, I might type ptt to have Keyboard Maestro type out padding-block-start: var(--spacing-somevalue), and place my cursor in the correct position so that DevTools presents me with a list of possible variables.

  2. Utilities such as deleting a line, moving lines up/down, commenting shortcuts, or maybe typing out a media query.

I've attached a sample of my macros below which may help you understand how to speed things up, before tailoring them to your needs.

If you'd like to understand a particular macro included in the attachment, hit me up on Twitter. Also, let me know if you have issues with any macros.

]]>
Tue, 09 Feb 2021 00:00:00 +0000
<![CDATA[Designing in the Browser by Mapping Devtools to Disk]]> https://jaygeorge.co.uk/blog/designing-in-the-browser https://jaygeorge.co.uk/blog/designing-in-the-browser In this post, we'll go through how to design in the browser with minimal friction, by mapping DevTools to your local disk. I also cover some bells and whistles, where you’ll see that DevTools is close to an IDE when it comes to CSS—actually, better since it has contextual awareness. NB To keep the video short, I've included some extra thoughts in the text that are not in the video.

I'm writing this post mostly because I think there is a perceptual misunderstanding when it comes to designing in the browser—typically that it's slow and awkward.

How to “Live Design” In the Browser

These instructions are for Chrome, but the process should be very similar for any other Chromium-based browser like Microsoft Edge.

  1. Open up DevTools on a local version of your site. A quick way to do this is by right-clicking anywhere on the page and selecting 'inspect'.

  2. Press the keyboard shortcut shift + ? to open up the DevTools preferences.

  3. Select Workspace from the left column, then select Add folder, then choose your site. At this point, I tend to dig a bit deeper and specifically select the folder where my CSS is housed since I don't want any other file results flagging up in DevTools. DevTools will ask your permission to map the folder at the top of the window; select Allow

That's kind of it! At this point when you look at the styles tab in the Elements pane, you'll see a load of green dots associated with the CSS files—this means that the file is successfully mapped.

Any changes you make in DevTools from now on will be automatically saved to disk.

NB you can also use a feature called local overrides to save HTML changes.

Advantages of This Workflow

  • Preview as you type—No need to hit cmd + s to actually see live changes—DevTools updates the preview realtime.

  • Inspect and edit in one sweep—Inspect, then click directly through to the line in the source. This is much easier and faster than remembering the line number, then looking it up in a text editor.

Feature Parity with Text Editors

Every developer loves their certain text editor for certain keyboard shortcuts or helpers. For CSS, however, DevTools should be a pretty comparable experience. Here are some of my favourite things.

  • Context-sensitive autocomplete—DevTools will show you values that are context-sensitive, e.g. if you type dispay: it'll suggest display values.

  • General autocomplete—You'll also be shown autocomplete when typing pretty much anything that is also in the same file like variables or properties.

  • Keyboard shortcuts—there are some excellent shortcuts available. When in the Elements tab hit shift + ? then select shortcuts on the left to view them all. Some of my favourites are:

    • alt + up/down to increment and decrement value – You can also use the shift modifier to increase/decrease by 10.

    • cmd + p to go to another file in your mapped folder. Comparable to VS Code and Sublime Text's Go To File command.

    • cmd + shift + p to open a command. Here you can search for lots of things such as emulating print-media or a dark mode preference.

  • Source Diff—If you're reading this at some time in the future this may be somewhere else, but for now, you can find this by going to the elements pane, pressing shift + ? to get to the preferences, then select Experiments and tick Source Diff

Advantages of Designing In the Browser Vs Using A More Visual tool

  • Render differences—Remember that text (and even colour) renders differently in the browser vs what you may see in a graphics application.

  • Version control—If you use Git designing in "code" is incredibly useful since you get a version control system built into your design.

  • Design System—CSS custom properties—or CSS variables as they're commonly referred to—ensure your design system is consistent. For example, I predefine spacing values and use them consistently throughout a website. I know you could argue that something like Adobe XD could give you this, but remember—so does CSS!

]]>
Wed, 03 Feb 2021 00:00:00 +0000
<![CDATA[Dynamic Cachebreaking Solution for Perch CMS]]> https://jaygeorge.co.uk/blog/dynamic-cachebreaking-solution-for-perch-cms https://jaygeorge.co.uk/blog/dynamic-cachebreaking-solution-for-perch-cms This article covers a solution for dynamically cache breaking static assets like JS and CSS, without needing a build process like Grunt or Gulp.

About Caching

Caching files is typically a good thing since it encourages the browser to reuse assets that have already been seen and cached to a temporary memory file.

A general best practice is to tell the browser to cache assets for a long time by setting header expires. Doing this means viewers do not need to re-download assets on repeat visits.

Problems with Caching

Caching can be a problem when you update your assets but the browser continues to serve the old ones because of the "header expires" you've set.

Caching Solutions

The solution to this caching problem is known as "cache-breaking", or sometimes "cache-busting". Cachebreaking involves changing the filename so the browser thinks there is a new asset to download.

For example, instead of trying to load style.min.css, we try to load style.min.1487201825.css. The browser thinks this is a brand new file, so it effectively resets the cache.

The typical way to deal with Cachebreaking is through an automated build process that changes the file names for you. You might do this through Grunt or Gulp for example.

If you're using a CMS such as Perch, however, since Perch runs on PHP which is dynamic, we can create our own caching solution using some PHP functions and rewrite rules.

Dynamic Cachebreaking in Perch

Part 1 — Serving a Filename Based on its Modified Time

The first thing we want to do is understand when our CSS or JS file was last modified. By understanding this we can prevent needlessly resetting/breaking the cache. We can get the last modified time by using the PHP filemtime function ("file modified time").

So in the PHP file which you're using to serve your assets (e.g. head.php) you would add a variable that gets the "last modified" time of a particular asset.

Get the last modified time of your CSS

The example below would get the last modified time of our minified CSS file. You should change this path to whatever's relevant for your particular setup.

$CSSversion = filemtime($SERVER['DOCUMENTROOT'].'/assets/css/style.min.css');

This variable would output a unique "last modified" time string such as 1487201825

We then want to call that variable when we call our asset. Here is an example:

<link rel="stylesheet" href="/assets/css/style.min.<?php echo $CSSversion ?>.css" type="text/css">

This would translate to:

<link rel="stylesheet" href="/assets/css/style.min.1487201825.css" type="text/css">

Get the last modified time of your JS

The example below would get the last modified time of our minified JS file. You should change this path to whatever's relevant for your particular setup.

$JSversion = filemtime($SERVER['DOCUMENTROOT'].'/assets/js/script.min.js');

This variable would output a unique "last modified" time string such as 1487201825.

We then want to call that variable when we call our asset. Here is an example:

<script src="/assets/js/script.min.<?php echo $JSversion ?>.js"></script>

This would translate to:

<script src="/assets/js/script.min.1487201825.js"></script>

In the above examples I'm covering both our CSS and JS assets but you can keep repeating the steps for different assets that you'd like to monitor.

So this takes care of breaking the cache whenever certain files have changed.

Part 2 — Rewriting Requests to Point to the Original Minified File

While the cache would effectively be reset/broken at this point, the problem is we don't actually have a file called style.min.1487201825.css! Instead, our file is just called style.min.css.

This is where you would ideally have a build process that would rename the file for you.

With an htaccess trick, we don't need that though. If you're running your site on an Apache server, the htaccess file is what's used to control any redirect or rewrite rules.

Your htaccess file is normally a "hidden" file at the root of your site, so make sure you have hidden files shown. Alternatively, if you have added a directory to a code editor like Sublime Text it will show hidden files for you.

In your htaccess file you'll need something like this:

<IfModule mod_rewrite.c>

    RewriteEngine on

    Options +FollowSymlinks

    # Cache Breaking

    # ---------------

    RewriteRule (assets/)([^.]*).min.+.(css|js)$ $1$2.min.$3

</IfModule>

As before, you should change the path to whatever's relevant for your particular setup. It's important we specify some of the paths so that we "ringfence" the rule. This prevents accidentally rewriting a plugin's CSS file or another directory in Perch.

An important note is that if you're using Perch Runway you'll need the cache breaking rules to appear above some of Runway's rules, so you might have something like this:

<IfModule mod_rewrite.c>
    RewriteEngine on
    Options +FollowSymlinks

    # Cache Breaking
    # ---------------
    RewriteRule (assets/)([^.]*).min.+.(css|js)$ $1$2.min.$3

    # Perch Runway <-- needs to come after Cache Breaking
    # --------------
    RewriteCond %{REQUEST_URI} !^/login
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule .* /login/core/runway/start.php [L]
</IfModule>

So what is our rule doing? It's looking for any path that starts with assets/ and ends with min.css or min.js. Htaccess is then rewriting that path, removing any middle ".something"'s, which means the "file modified time" number we inserted is written out.

If you inspect your page, we'll still see our style.min.1487201825.css example is showing but behind the scenes, it's been rewritten to style.min.css

You can play with this rule on Regexr (note that I've had to wrap square brackets around forward slashes on Regexr, but you shouldn't need these in your htaccess).

Notes

  1. You could skip step 2 if you want to cache break using a query string e.g. <link rel="stylesheet" href="/assets/css/style.min.css?v=1487201825" type="text/css">, however, this does not seem as favourable as renaming the file because some delivery services do not automatically treat files with a query string as a new asset

  2. This is a great article for further reading on automatic versioning

Credits

Thanks to Martin Underhill for his suggestion to use PHP to cache-bust, Duncan Revell for his Regex help, and Caden Peters for his suggestion to rewrite in htaccess rather than use a query string.

]]>
Thu, 16 Feb 2017 00:00:00 +0000
<![CDATA[Designing in DevTools Talk]]> https://jaygeorge.co.uk/blog/designing-in-devtools-talk https://jaygeorge.co.uk/blog/designing-in-devtools-talk Through different examples, in this talk, I hope to convince you that DevTools is a great place to design for the web, and should be your go-to tool for writing CSS.

I've given this talk a couple of times now, at both Digital Croydon and an ASOS Community Event. I've only given three talks before and it's been a learning process—it certainly gets easier with every talk.

Credit goes to https://umaar.com for some of the GIFs. If you want to keep up on the latest DevTools tricks I recommend his DevTools blog.

]]>
Fri, 27 Jan 2017 00:00:00 +0000
<![CDATA[Vertical Rhythm with Ems and Rems]]> https://jaygeorge.co.uk/blog/vertical-rhythm-with-ems-and-rems https://jaygeorge.co.uk/blog/vertical-rhythm-with-ems-and-rems There are already some tutorials on creating "Vertical Rhythm", most noticeably by Harry Roberts in his articles Single Direction Margins and Measuring and Sizing UIs and Richard Rutter's 2006 article Compose to a Vertical Rhythm.

I mostly wanted to expand on these and cover a few different examples, and more importantly, some gotchas that stopped me picking this up as quickly as I should have. Maybe you've arrived here as a sceptic. Maybe you're scoffing pixel pies and laughing at the complicated em-based maths you'll find here. Well, maybe I wasn't ever that cynical, but I certainly put off looking at ems for a long time.

My Background

I've long resisted moving from Pixels to Ems. I was in the 'I could do without the maths' camp.

That's not to say I was dogmatic about ems; I could appreciate the advantage of bumping font sizes in one go. But being frank I would rather change multiple fixed font sizes than figure out all the maths.

A few things eventually guilted me into giving them another chance, and if you're still bloody-minded, consider the following:

  • If you're designing responsively, you would likely have at least made the mental jump between designing with fixed-width containers to designing with % containers. It might have been a bit of effort to adjust, but it was worth it, right? Then it would help if you also were questioning your beliefs on using fixed pixels for font size.

  • Question when you should ever use fixed pixels. To design responsively is to create relationships between different elements. If your viewport expands, you probably want your main container to expand, albeit with a max-width. When your font size expands, so should your vertical paragraph padding, right? Thinking about these relationships is what convinced me to give ems another look.

  • If you look at the most influential web speakers and writers on Twitter, most, if not all, of them favour ems or rems. Whilst I'm not too fond of web celeb pandering when many of your web heroes hold a particular opinion you should question why that is.

Reading

Read these articles if you want to ponder further...

  1. Flexible Foundations by Trent Walton

  2. Why Ems by Chris Coyier

Establishing a Baseline with P tags

We'll start by just getting our vertical rhythm using just p tags. Nice and easy, hey?

The first thing you need to do is set your font-size to 100%. This does make sure you're starting with the default font size used by browsers, which tends to be 16px. E.g. 100% would equal 16px, 150% = 24px, 200% = 32px, etc.

If you've downloaded the HTML5 Boilerplate as a starting point for your project, this is done for you in their reset. I tend to repeat this rule in the main section of my style.css anyway, just for easy access.

html {
  font-size: 100%;
}

Our next step is to specify line-height. To be honest, line-height is pretty arbitrary. Your typeface and the sense of space in your design will affect your judgement here, but generally, 1.3 to 1.5 is considered optimal.

html {
   font-size: 100%;
   line-height: 1.5; /* Magic Number / Line-height value of 24px */
}

Using these two values, we can derive our baseline figure; what Harry Roberts calls our 'Magic Number'. This is basically what we'll be using to set the rest of our proportions to create consistent rhythm.

In this case, our baseline will be 24px. You get this number by times' your font size by the line-height, e.g. since we are using 100% to get the browser default of 16px, in our case, it would be 16px * 1.5 = 24px. This makes sense if you think about it, we're saying 'times our font-size of 16 pixels by 1 and a half to get the total height for the line'.

The only other thing we need to do is set a margin-block-end property on our p tags. This needs to be a multiple of our baseline, i.e. a multiple of 24px in our instance. So let's set this to 1.5rem (16 * 1.5= 24px).

*FYI: We're using rems just to avoid any nesting complications that initially put people off the em unit, to begin with. If you want to know more about the difference between ems and rems, read Snook's article.*

So that's it; we've created vertical rhythm with p tags. But how do we test this? There are many tools to do this, Dan Eden's baseline.js, for example, but I really like xScope, a Mac design app that you can use for lots of things besides testing baselines. I like it over other tools because you can set a global hotkey to toggle it off and on quickly.

In xScope, you can set a baseline step by going to Guides > Guide Wizard in the menu. Then set the orientation to horizontal, bump Repeat guide to 50 and set moving gutter to the baseline figure we have, i.e. 24. Make sure the gutter has been set to 0, and click 'Create Guide.'

]]>
You'll see the h2 is tighter to the next paragraph in the screenshot above.
]]>
With this, we can see that our p tags perfectly fit a 24px baseline
]]> Establishing a Baseline with H tags

Now we're getting the hang of things, right? Other elements should be easy, but this is where you'll hit gotcha number 1 if you're not paying attention.

Let's say we want to add an H2 tag. What you need to know is HTML5 Boilerplate adds some default margins to H tags, and so does the browser naturally; therefore, we need to set a margin-block-end value for the h2, but we also need to reset the margin-block-start value.

To solve this as we style subsequent elements, you can either reset all top and bottom margins using a group selector to start each project with or add them one by one as you use them. I'd suggest you reset them one by one just in case you miss a style. Otherwise, your reset will kill some safe defaults.

We'll add the h2 to our vertical margin reset and pick our font-size...

/* Reset. Add elements to this Reset as you build up your vertical rhythm */
h2,
p {
  margin: 0 auto;
}

h2 {
  font-size: 2rem; / 32px /
}

You'll see I have put a pixel calculation next to the font-size for future reference. The thing to bear in mind is that once these first calculations have been completed, we never need to worry about them again because in later media queries we just bump the font-size up on the HTML selector.

You get the REM font-size by taking your chosen pixel font-size and dividing it by the initial html font-size we chose. In our case we chose the default 100% (or 16px) for our initial font-size, therefore for a font-size of 32px that would be 32px / 16px = 2rem.

Just so we have another example, if you chose 36px for your h2 font-size, this would be a rem calculation of 2.25rem (36px / 16px).

Gotcha Number 2: Always work with the font pixel size first so you can easily keep things in line with the magic number, e.g. if you arbitrary decide on on a rem figure like 2.2rem, this might give you an odd pixel calculation of 35.2px, which would throw off your vertical rhythm.

To set up the proceeding vertical rhythm, we'll need to add a margin-block-end property of 1.5rem, which falls in line as a multiple of our 24px baseline (1.5 * 16px = 24px)

h2 {font-size: 2rem; /* 32px */
   margin-block-end: 1.5rem;
}
]]>
We'll talk about adjusting h2 proportions in the next section, but you can see from the screenshot above any subsequent p tags will now fall back in line with our vertical rhythm.
]]> Adjusting Rhythm Breaks

Once we have the vertical rhythm working between p tags and h tags, we can play with adjusting the breaks' height.

What I mean by this is, for me, the Heading 2 in the screenshot above feels wrong. The distance between the heading 2 + the previous/next paragraphs is the same. This makes the heading feel disconnected, and you're not sure which paragraph it belongs to. I see this on a lot of websites and dislike it. However, we can change it with a bit of maths.

The simplest way to do it is to add some padding above the h2. We just need to make sure it is a multiple of the baseline. Therefore we can add padding-top of 1.5rem, which is equal to our baseline of 24px (16px * 1.5 = 24px). This pushes our heading 2 away from the previous paragraph while maintaining our rhythm.

]]> ]]> We can also compress the line-height. Again, we just need to make sure the baseline is always a multiple of 24px.

h2 {
      font-size: 2rem; /* 32px */
      line-height: 0.75; /* 24px / 32px */
}
]]>
You'll see the h2 is tighter to the next paragraph in the screenshot above.
]]> Our maths has all been really clean so far, but if we want to increase our font size, it looks a lot more complicated. Again though, the maths is simple, it just looks complicated.

Here are our maths if we wanted to bump the font size of h2s up to 37px:

h2 {
    font-size: 2.3125rem;  /* 37px */
    line-height: 1.297297297; /* We need to get to a multiple of 24px, therefore 48px/37px. Alternatively we could pull compress the line height by going down to a lower multiple: 24px/37px = .648648649 */
}
]]>
Here is a screenshot of the same vertical rhythm, but with a larger h2, as above
]]> Hopefully, this gives you a good few examples of how you can achieve vertical rhythm through rems.

Taking the time to set this up will initially feel like a chore, but will save us maintenance later. For example, if we bump up the HTML font-size to 110% in a subsequent media query, our vertical rhythm will stay intact, with all paddings and font-sizes increasing proportionally. I think fixed pixels appear easier initially, and maybe less complex, but if you value the rhythm and proportion of your design, you should design responsively, relative units are your friends.

]]>
Sun, 03 Mar 2013 00:00:00 +0000