CSS Basics: The Second “S” in CSS

CSS is an abbreviation for Cascading Style Sheets.
While most of the discussion about CSS on the web (or even here on CSS-Tricks) is centered around writing styles and how the cascade affects them, what we don't talk a whole lot about is the sheet part of the language. So let's give that lonely second "S" a little bit of the spotlight and understand what we mean when we say CSS is a style sheet.

The Sheet Contains the Styles
The cascade describes how styles interact with one another. The styles make up the actual code. Then there's the sheet that contains that code. Like a sheet of paper that we write on, the "sheet" of CSS is the digital file where styles are coded.
If we were to illustrate this, the relationship between the three sort of forms a cascade:
The sheet holds the styles.
There can be multiple sheets all continuing multiple styles all associated with one HTML document. The combination of those and the processes of figuring out what styles take precedence to style what elements is called the cascade (That first "C" in CSS).
The Sheet is a Digital File
The sheet is such a special thing that it's been given its own file extension: .css. You have the power to create these files on your own. Creating a CSS file can be done in any text editor. They are literally text files. Not "rich text" documents or Word documents, but plain ol' text.
If you're on Mac, then you can fire up TextEdit to start writing CSS. Just make sure it's in "Plain Text" mode.

If you're on Windows, the default Notepad app is the equivalent. Heck, you can type styles in just about any plain text editor to write CSS, even if that's not what it says it was designed to do.
Whatever tool you use, the key is to save your document as a .css file. This can usually be done by simply add that to your file name when saving. Here's how that looks in TextEdit:

Seriously, the choice of which text editor to use for writing CSS is totally up to you. There are many, many to choose from, but here are a few popular ones:

Sublime Text
Atom
VIM
PhpStorm
Coda
Dreamweaver

You might reach for one of those because they'll do handy things for you like syntax highlight the code (colorize different parts to help it be easier to understand what is what).
Hey look I made some files completely from scratch with my text editor:

Those files are 100% valid in any web browser, new or old. We've quite literally just made a website.
The Sheet is Linked Up to the HTML
We do need to connect the HTML and CSS though. As in make sure the styles we wrote in our sheet get loaded onto the web page.
A webpage without CSS is pretty barebones:
See the Pen Style-less Webpage by Geoff Graham (@geoffgraham) on CodePen.
Once we link up the CSS file, voila!
See the Pen Webpage With Styles by Geoff Graham (@geoffgraham) on CodePen.
How did that happen? if you look at the top of any webpage, there's going to be a <head> tag that contains information about the HTML document:
<!DOCTYPE html>
<html>
<head>
<!-- a bunch of other stuff -->
</head>

<body>
<!-- the page content -->
</body>

</html>
Even though the code inside the <head> might look odd, there is typically one line (or more, if we're using multiple stylesheets) that references the sheet. It looks something like this:
<head>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
This line tells the web browser as it reads this HTML file:

I'd like to link up a style sheet
Here's where it is located

You can name the sheet whatever you want:

styles.css
global.css
seriously-whatever-you-want.css

The important thing is to give the correct location of the CSS file, whether that's on your web server, a CDN or some other server altogether.
Here are a few examples:
<head>
<!-- CSS on my server in the top level directory -->
<link rel="stylesheet" type="text/css" href="styles.css">

<!-- CSS on my server in another directory -->
<link rel="stylesheet" type="text/css" href="/css/styles.css">

<!-- CSS on another server -->
<link rel="stylesheet" type="text/css" href="https://some-other-site/path/to/styles.css">
</head>
The Sheet is Not Required for HTML
You saw the example of a barebones web page above. No web page is required to use a stylesheet.
Also, we can technically write CSS directly in the HTML using the HTML style attribute. This is called inline styling and it goes a little something like this if you imagine you're looking at the code of an HTML file:
<h1 style="font-size: 24px; line-height: 36px; color: #333333">A Headline</h1>
<p style="font-size: 16px; line-height: 24px; color: #000000;">Some paragraph content.</p>
<!-- and so on -->
While that's possible, there are three serious strikes against writing styles this way:

If you decide to use a stylesheet later, it is extremely difficult to override inline styles with the styles in the HTML. Inline styles take priority over styles in a sheet.
Maintaining all of those styles is tough if you need to make a "quick" change and it makes the HTML hard to read.
There's something weird about saying we're writing CSS inline when there really is no cascade or sheet. All we're really writing are styles.

There is a second way to write CSS in the HTML and that's directly in the <head> in a <style> block:
<head>
<style>
h1 {
color: #333;
font-size: 24px;
line-height: 36px;
}

p {
color: #000;
font-size: 16px;
line-height: 24px;
}
</style>
</head>
That does indeed make the HTML easier to read, already making it better than inline styling. Still, it's hard to manage all styles this way because it has to be managed on each and every webpage of a site, meaning one "quick" change might have to be done several times, depending on how many pages we're dealing with.
An external sheet that can be called once in the <head> is usually your best bet.
The Sheet is Important
I hope that you're starting to see the importance of the sheet by this point. It's a core part of writing CSS. Without it, styles would be difficult to manage, HTML would get cluttered, and the cascade would be nonexistent in at least one case.
The sheet is the core component of CSS. Sure, it often appears to play second fiddle to the first "S" but perhaps that's because we all have an quiet understanding of its importance.
Leveling Up
Now that you're equipped with information about stylesheets, here are more resources you jump into to get a deeper understanding for how CSS behaves:

Specifics on Specificity - The cascade is a confusing concept and this article breaks down the concept of specificity, which is a method for how to manage it.
The latest ways to deal with the cascade, inheritance and specificity - That's a lot of words, but the this article provides pro tips on how to manage the cascade, including some ideas that may be possible in the future.
Override Inline Styles with CSS - This is an oldie, but goodie. While the technique is probably not best practice today, it's a good illustration of how to override those inline styles we mentioned earlier.
When Using !important is The Right Choice - This article is a perfect call-and-response to the previous article about why that method may not be best practice.

CSS Basics: The Second “S” in CSS is a post from CSS-Tricks
Source: CssTricks


Observable

Observable launched a couple of weeks ago. As far as I understand, it’s sort of like a mix between CodePen and Medium where you create "notebooks" for exploring data, making nifty visualizations.

Check out this collection of visualizations using map integrations as an example. The entries are not only nice demos of the libraries or technology being used (i.e. D3, Google Maps, Leaflet, etc.), but also make for some interesting infographics in themselves.
In a note about this interesting new format, founder Mike Bostock describes a notebook as “an interactive, editable document defined by code. It’s a computer program, but one that’s designed to be easier to read and write by humans.”
All of this stuff riffs on a lot of Mike’s previous work which is definitely worth exploring further if you’re a fan of complex visualizations on the web.
Direct Link to Article — Permalink
Observable is a post from CSS-Tricks
Source: CssTricks


CSS Grid Layout Module Level 2

The second iteration of CSS Grid is already in the works and the public editor's draft was released last week! While it is by no means the final W3C recommendation, this draft is the start of discussions around big concepts many of us have been wanting to see since the first level was released, including subgrids:
In some cases it might be necessary for the contents of multiple grid items to align to each other. A grid container that is itself a grid item can defer the definition of its rows and columns to its parent grid container, making it a subgrid. In this case, the grid items of the subgrid participate in sizing the grid of the parent grid container, allowing the contents of both grids to align.

The currently defined characters of subgrid items are particularly interesting because they illustrate the differences between a subgrid and its parent grid. For example:
The subgrid is always stretched in both dimensions in its subgridded dimension(s): the align-self/justify-self properties on it are ignored, as are any specified width/height constraints.
In addition to subgrids, aspect-ratio-controlled gutters and conformance are also defined in the draft and worth a read. It's great to see so much momentum around grids!
Direct Link to Article — Permalink
CSS Grid Layout Module Level 2 is a post from CSS-Tricks
Source: CssTricks


CSS Basics: The Syntax That Matters & The Syntax That Doesn’t

When you're starting to play around with CSS at the very beginning, like any other language, you have to get used to the syntax. Like any syntax, there are a bunch of little things you need to know. Some characters and the placement of them is very important and required for the CSS to work correctly. And some characters are more about clean looking code and generally followed standards but don't matter for the CSS to work.

First, so we have the terminology down:
A CSS ruleset consists of a selector and delcaration(s) wrapped in curly braces.
Important: Braces
All CSS rulesets must have opening and closing curly braces:
braces.header { padding: 20px;}.header padding: 20px;}.header { padding: 20px;}.header padding: 20px;
If you miss the opening brace, CSS will keep reading as if the next bit of text is still part of the selector. Then it's likely to find a character like : which are invalid as part of a selector and break. Breaking likely means it will screw up itself and the next ruleset, and recover after that.
Missing a closing brace is a bit worse in that it's likely to mess up the rest of the entire CSS file unless it somehow finds a double closing brace and can resolve that first missing one.
Overall point: braces are very important!
Preprocessing languages like Sass and Less offer a syntax feature called nesting. This can be convenient, but note that when these preprocessors run and produce CSS, that nesting is removed because CSS by itself doesn't support that. If you copy nested CSS into regular CSS, you'll have problems with the braces.
Sometimes Important: Spaces
There are just a few places that spaces are important in CSS. One of the most imortant is in selectors. One space in a selector means you're selecting descendants of the previous part of the selector. The selector body p means "select p elements that are descendants of the body element". That space means a lot. Hopefully it's clearly different than bodyp which won't select anything (there is no <bodyp> element). But it's not different from body p. Multiple spaces mean the same as one space.
spacesbody ul libodyulli.header .title.header .title.header .title.header.title≠≠=
You can't put spaces in properties, function names, or anywhere you name things. Adding spaces in those situations effectively changes the names, breaking them.
spaces-3background-image: url(tiger.jpg);background - image: url(tiger.jpg);background-image: url (tiger.jpg);@keyframes goRoundAndRound { }@keyframes go-round-and-round { }@keyframes go round and round { }:root { --theme main: red; --theme-second: red;}body { background: var(--theme main); background: var(--theme-second);}
Other than that, spacing doesn't matter much in CSS.
spaces_1.header { padding: 20px;}.header { padding:20px; } .header {padding: 20px; }.header{padding: 20px; }.header{ padding: 20px;}.header{padding:20px;}
I'd encourage you to be consistent with your spacing, and produce clean and readable CSS. You might want to reference some CSS style guides out there for some formatting best practices.
Even the !important rule in CSS, which comes after a the value in a delcaration like body { background: white !important; } doesn't have any spacing requirements. It could have any amount of space before it, or none.
The removing of space in CSS is actually a best practice for performance, so you might notice that when peeking at the raw CSS of websites in production.

You're better off leaving that minification of CSS to a tool that processes your CSS for you, leaving the original alone. We'll have to cover the options for that in other post.
Mostly Important: Semicolons
Each declaration in a ruleset (a property and value pair) ends in a semicolon. That semicolon is required, otherwise CSS will keep reading the next property as if it's part of the value of the previous declaration.
semicolons.header { padding: 20px; max-width: 600px; background: black; color: white}.header { padding: 20px; max-width: 600px background: black; color: white;}
You can leave off the semicolon on the last declaration in a ruleset. I'd warn that doing so manually will cause more trouble than it's worth, and best left to minification tools.
Important: Avoiding Stray Characters
This is important in any language. Every character in code matters, so random other characters will almost certainly break things.
extra-chars.header { padding: 20px;}.header { { padding: 20px;}.header { padding: ~20px;}.header { /padding: 20px;}
Not Important: Line Breaks
A line break is treated like any other white space in CSS, so feel free to use them as needed, as long as it doesn't break any other spacing rule like we talked about above.
line-breaks.bar { background-image: url(texture.png), url(tiger.jpg); }.button::after { content: ">";} .header { box-shadow: 0 0 5px rgba(0, 0, 0, 0.5), 20px 2px 5px -5px rgba(0, 0, 0, 0.5);}

All in all, CSS syntax isn't so hard. Good luck!

CSS Basics: The Syntax That Matters & The Syntax That Doesn’t is a post from CSS-Tricks
Source: CssTricks


Stimulus

A modest JavaScript framework for the HTML you already have.
This will appeal to anyone who is apprehensive about JavaScript being required to generate HTML, yet wants a modern framework to help with modern problems, like state management.
I wonder if this would be a good answer for things like WordPress or CraftCMS themes that are designed to be server side but, like any site, could benefit from client-side JavaScript enhancements. Stimulus isn't really built to handle SPAs, but instead pair with Turbolinks. That way, you're still changing out page content with JavaScript, but all the routing and HTML generation is server side. Kinda old school meets new school.
Direct Link to Article — Permalink
Stimulus is a post from CSS-Tricks
Source: CssTricks


Stimulus

A modest JavaScript framework for the HTML you already have.
This will appeal to anyone who is apprehensive about JavaScript being required to generate HTML, yet wants a modern framework to help with modern problems, like state management.
I wonder if this would be a good answer for things like WordPress or CraftCMS themes that are designed to be server side but, like any site, could benefit from client-side JavaScript enhancements. Stimulus isn't really built to handle SPAs, but instead pair with Turbolinks. That way, you're still changing out page content with JavaScript, but all the routing and HTML generation is server side. Kinda old school meets new school.
Direct Link to Article — Permalink
Stimulus is a post from CSS-Tricks
Source: CssTricks


Article Performance Leaderboard

A clever idea from Michael Donohoe: pit websites against each other in a performance battle! Donohoe is a long-time newsroom guy, so this is specifically about article pages for major publications.

Lets state the obvious, this is an imperfect and evolving measure and the goal is to foster discussion and rivalry in making our pages better, faster, and lighter. Bear in mind this was built as an internal tool at Hearst Newspapers to track changes as we rollout our new Article template on mobile for SFGate and eventually all sites (SF Chronicle, Houston Chronicle, Times Union, etc).
Developers, designers, and product need to talk more on how to achieve this. A 1,700 word article might weigh 10KB but by the time you load HTML, JS, CSS, images, 3rd-parties, and ads, it can range between 2MB to 8MB depending on the web site. Bear in mind, the first Harry Potter ebook is 1.1MB and that includes cover art.

Interested in how it works? Learn about how to use the WebPageTest API or even spin up a service of your own.
Direct Link to Article — Permalink
Article Performance Leaderboard is a post from CSS-Tricks
Source: CssTricks


PixelSnap

Forever I've used the macOS Command-Shift-4 screenshot utility to measure things. Pressing it gets you a little crosshairs cursor which you can click-and-drag to take a screenshot but, crucially, has little numbers that tell you the width/height of the selection in pixels. It's crude, but ever so useful.

See those teeny-tiny numbers in the bottom-right? So useful, even if they are tough to read.
PixelSnap is one of those apps that, once you see it, you're like OMG that's the best idea ever. It's the same kind of interaction (key command, then mouse around), but it's drawing lines between obvious measurement points in any window at all. Plus it has this drag around and area and snap to edges thing that's just as brilliant. Instant purchase for me.
The Product Hunt newsletter said:
Two teenage makers launched PixelSnap, a powerful design tool to measure every pixel on your screen. Hit #1 on Product Hunt, and over $5,000 in sales within 24 hours of their launch. 📝✨
Hey, even cooler!
A couple people pointed out xScope, which also has this feature. Fifty bucks, but also has a ton of other features. Tempting.
Direct Link to Article — Permalink
PixelSnap is a post from CSS-Tricks
Source: CssTricks


Direction Aware Hover Effects

This is a particular design trick that never fails to catch people's eye! I don't know the exact history of who-thought-of-what first and all that, but I know I have seen a number of implementations of it over the years. I figured I'd round a few of them up here.

Noel Delagado
See the Pen Direction-aware 3D hover effect (Concept) by Noel Delgado (@noeldelgado) on CodePen.
The detection here is done by tracking the mouse position on mouseover and mouseout and calculating which side was crossed. It's a small amount of clever JavaScript, the meat of which is figuring out that direction:
var getDirection = function (ev, obj) {
var w = obj.offsetWidth,
h = obj.offsetHeight,
x = (ev.pageX - obj.offsetLeft - (w / 2) * (w > h ? (h / w) : 1)),
y = (ev.pageY - obj.offsetTop - (h / 2) * (h > w ? (w / h) : 1)),
d = Math.round( Math.atan2(y, x) / 1.57079633 + 5 ) % 4;

return d;
};
Then class names are applied depending on that direction to trigger the directional CSS animations.
Fabrice Weinberg
See the Pen Direction aware hover pure CSS by Fabrice Weinberg (@FWeinb) on CodePen.
Fabrice uses just pure CSS here. They don't detect the outgoing direction, but they do detect the incoming direction by way of four hidden hoverable boxes, each rotated to cover a triangle. Like this:

Codrops
Demo
In an article by Mary Lou on Codrops from 2012, Direction-Aware Hover Effect with CSS3 and jQuery, the detection is also done in JavaScript. Here's that part of the plugin:
_getDir: function (coordinates) {
// the width and height of the current div
var w = this.$el.width(),
h = this.$el.height(),
// calculate the x and y to get an angle to the center of the div from that x and y.
// gets the x value relative to the center of the DIV and "normalize" it
x = (coordinates.x - this.$el.offset().left - (w / 2)) * (w > h ? (h / w) : 1),
y = (coordinates.y - this.$el.offset().top - (h / 2)) * (h > w ? (w / h) : 1),
// the angle and the direction from where the mouse came in/went out clockwise (TRBL=0123);
// first calculate the angle of the point,
// add 180 deg to get rid of the negative values
// divide by 90 to get the quadrant
// add 3 and do a modulo by 4 to shift the quadrants to a proper clockwise TRBL (top/right/bottom/left) **/
direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4;
return direction;
},
It's technically CSS doing the animation though, as inline styles are applied as needed to the elements.
John Stewart
See the Pen Direction Aware Hover Goodness by John Stewart (@johnstew) on CodePen.
John leaned on Greensock to do all the detection and animation work here. Like all the examples, it has its own homegrown geometric math to calculate the direction in which the elements were hovered.
// Detect Closest Edge
function closestEdge(x,y,w,h) {
var topEdgeDist = distMetric(x,y,w/2,0);
var bottomEdgeDist = distMetric(x,y,w/2,h);
var leftEdgeDist = distMetric(x,y,0,h/2);
var rightEdgeDist = distMetric(x,y,w,h/2);
var min = Math.min(topEdgeDist,bottomEdgeDist,leftEdgeDist,rightEdgeDist);
switch (min) {
case leftEdgeDist:
return "left";
case rightEdgeDist:
return "right";
case topEdgeDist:
return "top";
case bottomEdgeDist:
return "bottom";
}
}

// Distance Formula
function distMetric(x,y,x2,y2) {
var xDiff = x - x2;
var yDiff = y - y2;
return (xDiff * xDiff) + (yDiff * yDiff);
}
Gabrielle Wee
See the Pen CSS-Only Direction-Aware Cube Links by Gabrielle Wee ✨ (@gabriellewee) on CodePen.
Gabrielle gets it done entirely in CSS by positioning four hoverable child elements which trigger the animation on a sibling element (the cube) depending on which one was hovered. There is some tricky stuff here involving clip-path and transforms that I admit I don't fully understand. The hoverable areas don't appear to be triangular like you might expect, but rectangles covering half the area. It seems like they would overlap ineffectively, but they don't seem to. I think it might be that they hang off the edges slightly giving a hover area that allows each edge full edge coverage.
Elmer Balbin
See the Pen Direction Aware Tiles using clip-path Pure CSS by Elmer Balbin (@elmzarnsi) on CodePen.
Elmer is also using clip-path here, but the four hoverable elements are clipped into triangles. You can see how each of them has a point at 50% 50%, the center of the square, and has two other corner points.
clip-path: polygon(0 0, 100% 0, 50% 50%)
clip-path: polygon(100% 0, 100% 100%, 50% 50%);
clip-path: polygon(0 100%, 50% 50%, 100% 100%);
clip-path: polygon(0 0, 50% 50%, 0 100%);
Nigel O Toole
Demo
Raw JavaScript powers Nigel's demo here, which is all modernized to work with npm and modules and all that. It's familiar calculations though:
const _getDirection = function (e, item) {
// Width and height of current item
let w = item.offsetWidth;
let h = item.offsetHeight;
let position = _getPosition(item);

// Calculate the x/y value of the pointer entering/exiting, relative to the center of the item.
let x = (e.pageX - position.x - (w / 2) * (w > h ? (h / w) : 1));
let y = (e.pageY - position.y - (h / 2) * (h > w ? (w / h) : 1));

// Calculate the angle the pointer entered/exited and convert to clockwise format (top/right/bottom/left = 0/1/2/3). See https://stackoverflow.com/a/3647634 for a full explanation.
let d = Math.round(Math.atan2(y, x) / 1.57079633 + 5) % 4;

// console.table([x, y, w, h, e.pageX, e.pageY, item.offsetLeft, item.offsetTop, position.x, position.y]);

return d;
};
The JavaScript ultimately applies classes, which are animated in CSS based on some fancy Sass-generated animations.
Giana
A CSS-only take that handles the outgoing direction nicely!
See the Pen CSS-only directionally aware hover by Giana (@giana) on CodePen.

Seen any others out there? Ever used this on something you've built?

Direction Aware Hover Effects is a post from CSS-Tricks
Source: CssTricks


Animating Border

Transitioning border for a hover state. Simple, right? You might be unpleasantly surprised.
The Challenge
The challenge is simple: building a button with an expanding border on hover.
This article will focus on genuine CSS tricks that would be easy to drop into any project without having to touch the DOM or use JavaScript. The methods covered here will follow these rules

Single element (no helper divs, but psuedo-elements are allowed)
CSS only (no JavaScript)
Works for any size (not restricted to a specific width, height, or aspect ratio)
Supports transparent backgrounds
Smooth and performant transition

I proposed this challenge in the Animation at Work Slack and again on Twitter. Though there was no consensus on the best approach, I did receive some really clever ideas by some phenomenal developers.
Method 1: Animating border
The most straightforward way to animate a border is… well, by animating border.
.border-button {
border: solid 5px #FC5185;
transition: border-width 0.6s linear;
}

.border-button:hover { border-width: 10px; }
See the Pen CSS writing-mode experiment by Shaw (@shshaw) on CodePen.
Nice and simple, but there are some big performance issues.
Since border takes up space in the document’s layout, changing the border-width will trigger layout. Nearby elements will shift around because of the new border size, making browser reposition those elements every frame of the animation unless you set an explicit size on the button.
As if triggering layout wasn’t bad enough, the transition itself feels “stepped”. I’ll show why in the next example.
Method 2: Better border with outline
How can we change the border without triggering layout? By using outline instead! You’re probably most familiar with outline from removing it on :focus styles (though you shouldn’t), but outline is an outer line that doesn’t change an element’s size or position in the layout.
.border-button {
outline: solid 5px #FC5185;
transition: outline 0.6s linear;
margin: 0.5em; /* Increased margin since the outline expands outside the element */
}

.border-button:hover { outline-width: 10px; }

A quick check in Dev Tools’ Performance tab shows the outline transition does not trigger layout. Regardless, the movement still seems stepped because browsers are rounding the border-width and outline-width values so you don’t get sub-pixel rendering between 5 and 6 or smooth transitions from 5.4 to 5.5.

Strangely, Safari often doesn’t render the outline transition and occasionally leaves crazy artifacts.

Method 3: Cut it with clip-path
First implemented by Steve Gardner, this method uses clip-path with calc to trim the border down so on hover we can transition to reveal the full border.
.border-button {
/* Full width border and a clip-path visually cutting it down to the starting size */
border: solid 10px #FC5185;
clip-path: polygon(
calc(0% + 5px) calc(0% + 5px), /* top left */
calc(100% - 5px) calc(0% + 5px), /* top right */
calc(100% - 5px) calc(100% - 5px), /* bottom right */
calc(0% + 5px) calc(100% - 5px) /* bottom left */
);
transition: clip-path 0.6s linear;
}

.border-button:hover {
/* Clip-path spanning the entire box so it's no longer hiding the full-width border. */
clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%);
}

clip-path technique is the smoothest and most performant method so far, but does come with a few caveats. Rounding errors may cause a little unevenness, depending on the exact size. The border also has to be full size from the start, which may make exact positioning tricky.
Unfortunately there’s no IE/Edge support yet, though it seems to be in development. You can and should encourage Microsoft’s team to implement those features by voting for masks/clip-path to be added.
Method 4: linear-gradient background
We can simulate a border using a clever combination of multiple linear-gradient backgrounds properly sized. In total we have four separate gradients, one for each side. The background-position and background-size properties get each gradient in the right spot and the right size, which can then be transitioned to make the border expand.
.border-button {
background-repeat: no-repeat;

/* background-size values will repeat so we only need to declare them once */
background-size:
calc(100% - 10px) 5px, /* top & bottom */
5px calc(100% - 10px); /* right & left */

background-position:
5px 5px, /* top */
calc(100% - 5px) 5px, /* right */
5px calc(100% - 5px), /* bottom */
5px 5px; /* left */

/* Since we're sizing and positioning with the above properties, we only need to set up a simple solid-color gradients for each side */
background-image:
linear-gradient(0deg, #FC5185, #FC5185),
linear-gradient(0deg, #FC5185, #FC5185),
linear-gradient(0deg, #FC5185, #FC5185),
linear-gradient(0deg, #FC5185, #FC5185);

transition: all 0.6s linear;
transition-property: background-size, background-position;
}

.border-button:hover {
background-position: 0 0, 100% 0, 0 100%, 0 0;
background-size: 100% 10px, 10px 100%, 100% 10px, 10px 100%;
}

This method is quite difficult to set up and has quite a few cross-browser differences. Firefox and Safari animate the faux-border smoothly, exactly the effect we’re looking for. Chrome’s animation is jerky and even more stepped than the outline and border transitions. IE and Edge refuse to animate the background at all, but they do give the proper border expansion effect.
Method 5: Fake it with box-shadow
Hidden within box-shadow's spec is a fourth value for spread-radius. Set all the other length values to 0px and use the spread-radius to build your border alternative that, like outline, won’t affect layout.
.border-button {
box-shadow: 0px 0px 0px 5px #FC5185;
transition: box-shadow 0.6s linear;
margin: 0.5em; /* Increased margin since the box-shado expands outside the element, like outline */
}

.border-button:hover { box-shadow: 0px 0px 0px 10px #FC5185; }

The transition with box-shadow is adequately performant and feels much smoother, except in Safari where it’s snapping to whole-values during the transition like border and outline.
Pseudo-Elements
Several of these techniques can be modified to use a pseudo-element instead, but pseudo-elements ended up causing some additional performance issues in my tests.
For the box-shadow method, the transition occasionally triggered paint in a much larger area than necessary. Reinier Kaper pointed out that a pseudo-element can help isolate the paint to a more specific area. As I ran further tests, box-shadow was no longer causing paint in large areas of the document and the complication of the pseudo-element ended up being less performant. The change in paint and performance may have been due to a Chrome update, so feel free to test for yourself.
I also could not find a way to utilize pseudo-elements in a way that would allow for transform based animation.
Why not transform: scale?
You may be firing up Twitter to helpfully suggest using transform: scale for this. Since transform and opacity are the best style properties to animate for performance, why not use a pseudo-element and have the border scale up & down?
.border-button {
position: relative;
margin: 0.5em;
border: solid 5px transparent;
background: #3E4377;
}

.border-button:after {
content: '';
display: block;
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
border: solid 10px #FC5185;
margin: -15px;
z-index: -1;
transition: transform 0.6s linear;
transform: scale(0.97, 0.93);
}

.border-button:hover::after { transform: scale(1,1); }

There are a few issues:

The border will show through a transparent button. I forced a background on the button to show how the border is hiding behind the button. If your design calls for buttons with a full background, then this could work.
You can’t scale the border to specific sizes. Since the button’s dimensions vary with the text, there’s no way to animate the border from exactly 5px to 10px using only CSS. In this example I’ve done some magic-numbers on the scale to get it to appear right, but that won’t be universal.
The border animates unevenly because the button’s aspect ratio isn’t 1:1. This usually means the left/right will appear larger than the top/bottom until the animation completes. This may not be an issue depending on how fast your transition is, the button’s aspect ratio, and how big your border is.

If your button has set dimensions, Cher pointed out a clever way to calculate the exact scales needed, though it may be subject to some rounding errors.
Beyond CSS
If we loosen our rules a bit, there are many interesting ways you can animate borders. Codrops consistently does outstanding work in this area, usually utilizing SVGs and JavaScript. The end results are very satisfying, though they can be a bit complex to implement. Here are a few worth checking out:

Creative Buttons
Button Styles Inspiration
Animated Checkboxes
Distorted Button Effects
Progress Button Styles

Conclusion
There’s more to borders than simply border, but if you want to animate a border you may have some trouble. The methods covered here will help, though none of them are a perfect solution. Which you choose will depend on your project’s requirements, so I’ve laid out a comparison table to help you decide.

My recommendation would be to use box-shadow, which has the best overall balance of ease-of-implementation, animation effect, performance and browser support.
Do you have another way of creating an animated border? Perhaps a clever way to utilize transforms for moving a border? Comment below or reach me on Twitter to share your solution to the challenge.
Special thanks to Martin Pitt, Steve Gardner, Cher, Reinier Kaper, Joseph Rex, David Khourshid, and the Animation at Work community.

Animating Border is a post from CSS-Tricks
Source: CssTricks


A Front End Developer’s Guide to GraphQL

No matter how large or small your application is, you’ll have to deal with fetching data from a remote server at some point. On the front end, this usually involves hitting a REST endpoint, transforming the response, caching it, and updating your UI. For years, REST has been the status quo for APIs, but over the past year, a new API technology called GraphQL has exploded in popularity due to its excellent developer experience and declarative approach to data fetching.
In this post, we’ll walk through a couple of hands-on examples to show you how integrating GraphQL into your application will solve many pain points working with remote data. If you’re new to GraphQL, don’t panic! I’ll also highlight some resources to help you learn GraphQL using the Apollo stack, so you can start off 2018 ahead of the curve.

GraphQL 101
Before we dive into how GraphQL makes your life as a front end developer easier, we should first clarify what it is. When we talk about GraphQL, we're either referring to the language itself or its rich ecosystem of tools. At its core, GraphQL is a typed query language developed by Facebook that allows you to describe your data requirements in a declarative way. The shape of your result matches the shape of your query: in the example below, we can expect to receive back an object with a currency property and a rates property containing an array of objects with both currency and rate keys.
{
rates(currency: "USD") {
currency
rates {
currency
rate
}
}
}
When we talk about GraphQL in a broader sense, we’re often referring to the ecosystem of tools that help you implement GraphQL in your application. On the backend, you’ll use Apollo Server to create a GraphQL server, which is a single endpoint that parses a GraphQL request and returns data. How does the server know which data to return? You’ll use GraphQL Tools to build a schema (like a blueprint for your data) and a resolver map (just a series of functions that retrieve your data from a REST endpoint, database, or wherever else you choose).
This all sounds more complicated than it actually is — with Apollo Launchpad, a GraphQL server playground, you can create a working GraphQL server in your browser in less than 60 lines of code! 😮 We’ll reference this Launchpad I created that wraps the Coinbase API throughout this post.
You’ll connect your GraphQL server to your application with Apollo Client, a fast and flexible client that fetches, caches, and updates your data for you. Since Apollo Client isn’t coupled to your view layer, you can use it with React, Angular, Vue, or plain JavaScript. Not only is Apollo cross-framework, it’s also cross-platform, with React Native & Ionic supported out of the box.
Let’s give it a try! 🚀
Now that you’re well-versed in what GraphQL is, let’s get our hands dirty with a couple of practical examples that illustrate what it’s like to develop your front end with Apollo. By the end, I think you’ll be convinced that a GraphQL-based architecture with Apollo can help you ship features faster than before.
1. Add new data requirements without adding a new endpoint
We’ve all been here before: You spend hours building a perfect UI component when suddenly, product requirements change. You quickly realize that the data you need to fulfill these new requirements would either require a complicated waterfall of API requests or worse, a new REST endpoint. Now blocked on your work, you ask the backend team to build you a new endpoint just to satisfy the data needs for one component.
This common frustration no longer exists with GraphQL because the data you consume on the client is no longer coupled to an endpoint’s resource. Instead, you always hit the same endpoint for your GraphQL server. Your server specifies all of the resources it has available via your schema and lets your query determine the shape of the result. Let’s illustrate these concepts using our Launchpad from before:
In our schema, look at lines 22–26 where we define our ExchangeRate type. These fields list out all the available resources we can query in our application.
type ExchangeRate {
currency: String
rate: String
name: String
}
With REST, you’re limited to the data your resource provides. If your /exchange-rates endpoint doesn’t include name, then you’ll need to either hit a different endpoint like /currency for the data or create it if it doesn’t exist.
With GraphQL, we know that name is already available to us by inspecting our schema, so we can query for it in our application. Try running this example in Launchpad by adding the name field on the right side panel!
{
rates(currency: "USD") {
currency
rates {
currency
rate
name
}
}
}
Now, remove the name field and run the same query. See how the shape of our result changes?

Your GraphQL server always gives you back exactly the data you ask for. Nothing more. This differs significantly from REST, where you often have to filter and transform the data you get back from the server into the shape your UI components need. Not only does this save you time, it also results in smaller network payloads and CPU savings from loading and parsing the response.
2. Reduce your state management boilerplate
Fetching data almost always involves updating your application’s state. Typically, you’ll write code to track at least three actions: one for when the data is loading, one if the data successfully arrives, and one if the data errors out. Once the data arrives, you have to transform it into the shape your UI components expect, normalize it, cache it, and update your UI. This process can be repetitive, requiring countless lines of boilerplate to execute one request.
Let’s see how Apollo Client eliminates this tiresome process altogether by looking at an example React app in CodeSandbox. Navigate to `list.js` and scroll to the bottom.
export default graphql(ExchangeRateQuery, {
props: ({ data }) => {
if (data.loading) {
return { loading: data.loading };
}
if (data.error) {
return { error: data.error };
}
return {
loading: false,
rates: data.rates.rates
};
}
})(ExchangeRateList);
In this example, React Apollo, Apollo Client’s React integration, is binding our exchange rate query to our ExchangeRateList component. Once Apollo Client executes that query, it tracks loading and error state automatically and adds it to the data prop. When Apollo Client receives the result, it will update the data prop with the result of the query, which will update your UI with the rates it needs to render.
Under the hood, Apollo Client normalizes and caches your data for you. Try clicking some of the currencies in the panel on the right to watch the data refresh. Now, select a currency a second time. Notice how the data appears instantaneously? That’s the Apollo cache at work! You get all of this for free just by setting up Apollo Client with no additional configuration. 😍 To see the code where we initialize Apollo Client, check out `index.js`.
3. Debug quickly & painlessly with Apollo DevTools & GraphiQL
It looks like Apollo Client does a lot for you! How do we peek inside to understand what’s going on? With features like store inspection and full visibility into your queries & mutations, Apollo DevTools not only answers that question, but also makes debugging painless and, dare I say it, fun! 🎉 It’s available as an extension for both Chrome and Firefox, with React Native coming soon.
If you want to follow along, install Apollo DevTools for your preferred browser and navigate to our CodeSandbox from the previous example. You’ll need to run the example locally by clicking Download in the top nav bar, unzipping the file, running npm install, and finally npm start. Once you open up your browser’s dev tools panel, you should see a tab that says Apollo.
First, let’s check out our store inspector. This tab mirrors what’s currently in your Apollo Client cache, making it easy to confirm your data is stored on the client properly.

Apollo DevTools also enables you to test your queries & mutations in GraphiQL, an interactive query editor and documentation explorer. In fact, you already used GraphiQL in the first example where we experimented with adding fields to our query. To recap, GraphiQL features auto-complete as you type your query into the editor and automatically generated documentation based on GraphQL’s type system. It’s extremely useful for exploring your schema, with zero maintenance burden for developers.

Try executing queries with GraphiQL in the right side panel of our Launchpad. To show the documentation explorer, you can hover over fields in the query editor and click on the tooltip. If your query runs successfully in GraphiQL, you can be 100% positive that the same query will run successfully in your application.
Level up your GraphQL skills
If you made it to this point, awesome job! 👏 I hope you enjoyed the exercises and got a taste of what it would be like to work with GraphQL on the front end.
Hungry for more? 🌮 Make it your 2018 New Year’s resolution to learn more about GraphQL, as I expect its popularity to grow even more in the upcoming year. Here’s an example app to get you started featuring the concepts we learned today:

React: https://codesandbox.io/s/jvlrl98xw3
Angular (Ionic): https://github.com/aaronksaunders/ionicLaunchpadApp
Vue: https://codesandbox.io/s/3vm8vq6kwq

Go forth and GraphQL (and be sure to tag us on Twitter @apollographql along the way)! 🚀

A Front End Developer’s Guide to GraphQL is a post from CSS-Tricks
Source: CssTricks


The Three Developers and the Insightful User Tester

A story by Scott O'Hara:

The first of the developers, why he thought he knew best.
“I’ll get this done ever so quick!” he said, puffing out his chest.
“While the others review wikis, knowledge bases, and specifications,
I’ll lean on my deep knowledge of CSS to circumvent such onerous proclamations.
Specificity will be lax, and BEM classes will be king!
Everyone will marvel at the CSS of this thing.

Direct Link to Article — Permalink
The Three Developers and the Insightful User Tester is a post from CSS-Tricks
Source: CssTricks


A Big List of Typography Books

For your holiday gift shopping needs! These my picks for some of the most popular books out there on typography, with a tilt toward web typography. Plus a couple of bonus picks by our own Robin Rendle.
Direct Link to Article — Permalink
A Big List of Typography Books is a post from CSS-Tricks
Source: CssTricks


24 Ways

24 Ways, the advent calendar for web geeks, started up again this week. Throughout December they’ll be publishing a wide range of posts all about web design, CSS, and front-end development.
Chen Hui Jing has already written a great post about feature queries and Stephanie Drescher published a post today about a tool called sonarwhal which identifies accessibility, performance and security issues, just to name a few.
And if you're into advent calendars, here's another 16 web integrationrelated ones.
Direct Link to Article — Permalink
24 Ways is a post from CSS-Tricks
Source: CssTricks


How the Roman Empire Made Pure CSS Connect 4 Possible

Experiments are a fun excuse to learn the latest tricks, think of new ideas, and push your limits. "Pure CSS" demos have been a thing for a while, but new opportunities open up as browsers and CSS itself evolves. CSS and HTML preprocessors also helped the scene move forward. Sometimes preprocessors are used for hardcoding every possible scenario, for example, long strings of :checked and adjacent sibling selectors.
In this article, I will walk through the key ideas of a Pure CSS Connect 4 game I built. I tried to avoid hardcoding as much as I could in my experiment and worked without preprocessors to focus on keeping the resulting code short. You can see all the code and the game right here:
See the Pen Pure CSS Connect 4 by Bence Szabó (@finnhvman) on CodePen.
Essential concepts
I think there are some concepts that are considered essential in the "pure CSS" genre. Typically form elements are used for managing state and capturing user actions. I was excited when I found people use <button type="reset"> to reset or start a new game. All you have to do is wrap your elements in a <form> tag and add the button. In my opinion this is a much cleaner solution than having to refresh the page.
My first step was to create a form element then throw a bunch of inputs into it for the slots and add the reset button. Here is a very basic demonstration of <button type="reset"> in action:
See the Pen Pure HTML Form Reset by Bence Szabó (@finnhvman) on CodePen.
I wanted to have nice visual for this demo to provide a full experience. Instead of pulling in an external image for the board or the discs, I used a radial-gradient(). A nice resource I often use is Lea Verou's CSS3 Patterns Gallery. It is a collection of patterns made by gradients, and they're editable too! I used currentcolor, which came pretty handy for the disc pattern. I added a header and reused my Pure CSS Ripple Button.
At this point the layout and disc design was already final, only the game didn't work at all
Dropping discs onto the board
Next I enabled users to take their turns dropping discs onto the Connect 4 board. In Connect 4, players (one red and one yellow) drop discs into columns in alternating turns. There are 7 columns and 6 rows (42 slots). Each slot can be empty or occupied by a red or yellow disc. So, a slot can have three states (empty, red, or yellow). Discs dropped in the same column are stacked onto each other.
I started out by placing two checkboxes for each slot. When they're both unchecked the slot is considered empty, and when one of them is checked the corresponding player has its disc in it.
The possible state of having them both checked should be avoided by hiding them once either of them is checked. These checkboxes are immediate siblings, so when the first of a pair is checked you can hide both by using :checked pseudo-class and the adjacent sibling combinator (+). What if the second is checked? You can hide the second one, but how to affect the first one? Well, there is no previous sibling selector, that's just not how CSS selectors work. I had to reject this idea.
Actually, a checkbox can have three states by itself, it can be in the indeterminate state. The problem is that you can't put it into indeterminate state with HTML alone. Even if you could, the next click on the checkbox would always make it transform into checked state. Forcing the second player to double-click when they make their move is unreliable and unacceptable.
I was stuck on the MDN doc of :indeterminate and noticed that radio inputs also have indeterminate state. Radio buttons with the same name are in this state when they're all unchecked. Wow, that's an actual initial state! What's really beneficial is that checking the latter sibling also has an effect on the former one! Thus I filled the board with 42 pairs of radio inputs.
In retrospect, clever ordering and usage of labels with either checkboxes or radio buttons would have made the trick, but I didn't consider labels to be an option to keep the code simpler and shorter.
I wanted to have large areas for interaction to have nice UX, so I thought it's reasonable to let players make a move by clicking on a column. I stacked controls of the same column on each other by adding absolute and relative positioning to the appropriate elements. This way only the lowest empty slot could be selected within a column. I meticulously set the time of transition of disc fall per row and their timing function is approximating a quadratic curve to resemble realistic free fall. So far the pieces of the puzzle came well together, though the animation below clearly shows that only the red player could make their moves.
Even though all the controls are there, only red discs can be dropped on the board
The clickable areas of radio inputs are visualized with colored but semi-transparent rectangles. The yellow and red inputs are stacked over each other six times(=six rows) per column, leaving the red input of the lowest row on top of the stack. The mixture of red and yellow creates the orangish color which can be seen on the board at start. The less empty slots are available in a column, the less intense this orangish color gets since the radio inputs are not displayed once they are not :indeterminate. Due to the red input always being precisely over the yellow input in every slot, only the red player is able to make moves.
Tracking turns
I only had a faint idea and a lot of hope that I can somehow solve switching turns between the two players with the general sibling selector. The concept was to let the red player take turn when the number of checked inputs was even (0, 2, 4, etc.) and let the yellow player take turn when that number was odd. Soon I realized that the general sibling selector does not (and should not!) work the way I wanted.
Then a very obvious choice was to experiment with the nth selectors. However attracting it was to use the even and odd keywords, I ran into a dead end. The :nth-child selector "counts" the children within a parent, regardless of type, class, pseudo-class, whatever. The :nth-of-type selector "counts" children of a type within a parent, regardless of class or pseudo-class. So the problem is that they cannot count based on the :checked state.
Well CSS counters count too, so why not give them a try? A common usage of counters is to number headings (even in multiple levels) in a document. They are controlled by CSS rules, can be arbitrarily reset at any point and their increment (or decrement!) values can be any integer. The counters are displayed by the counter() function in the content property.
The easiest step was to set up a counter and count the :checked inputs in the Connect 4 grid. There are only two difficulties with this approach. The first is you cannot perform arithmetics on a counter to detect if its is even or odd. The second is that you cannot apply CSS rules to elements based on the counter value.
I managed to overcome the first issue by making the counter binary. The value of the counter is initially zero. When the red player checks their radio button the counter is incremented by one. When the yellow player checks their radio button the counter is decremented by one, and so on. Therefore the counter value will be either zero or one, even or odd.
Solving the second problem required much more creativity (read: hack). As mentioned counters can be displayed, but only in the ::before and ::after pseudo-elements. That is a no-brainer, but how can they affect other elements? At the very least the counter value can change the width of the pseudo-element. Different numbers have different widths. Character 1 is typically thinner than 0, but that is something very hard to control. If the number of characters change rather than the character itself the resulting width change is more controllable. It is not uncommon to use Roman numerals with CSS counters. One and two represented in Roman numerals are the same character once and twice and so are their widths in pixels.
My idea was to attach the radio buttons of one player (yellow) to the left, and attach the radio buttons of the other player (red) to the right of their shared parent container. Initially, the red buttons are overlaid on the yellow buttons, then the width change of the container would cause the red buttons to "go away" and reveal the yellow buttons. A similar real-world concept is the sliding window with two panes, one pane is fixed (yellow buttons), the other is slidable (red buttons) over the other. The difference is that in the game only half of the window is visible.
So far, so good, but I still wasn't satisfied with font-size (and the other font properties) indirectly controlling the width. I thought letter-spacing would fit nicely here, since it only increases the size in one dimension. Unexpectedly, even one letter has letter spacing (which is rendered after the letter), and two letters render the letter spacing twice. Predictable widths are crucial to make this reliable. Zero width characters along with single and double letter spacing would work, but it is dangerous to set the font-size to zero. Defining large letter-spacing (in pixels) and tiny (1px) font-size made it almost consistent across all browsers, yes I'm talking about sub-pixels.
I needed the container width to alternate between initial size (=w) and at least double the initial size (>=2w) to be able to fully hide and show the yellow buttons. Let's say v is the rendered width of the 'i' character (lower roman representation, varies across browsers), and c is the rendered width (constant) of the letter-spacing. I needed v + c = w to be true but it couldn't be, because c and w are integers but v is non-integer. I ended up using min-width and max-width properties to constrain the possible width values, so I also changed the possible counter values to 'i' and 'iii' to make sure the text widths underflow and overflow the constraints. In equations this looked like v + c < w, 3v + 3c > 2w, and v << c, which gives 2/3w < c < w. The conclusion is that the letter-spacing has to be somewhat smaller than the initial width.
I have been reasoning so far as if the pseudo element displaying the counter value was the parent of the radio buttons, it is not. However, I noticed that the width of the pseudo-element changes the width of its parent element, and in this case the parent is the container of the radio buttons.
If you are thinking couldn't this be solved with Arabic numerals? You are right, alternating the counter value between something like '1' and '111' would also work. Nevertheless, Roman numerals gave me the idea in the first place, and they were also a good excuse for the clickbaity title so I kept them.
The players take alternating turns starting with the red player
Applying the technique discussed makes the parent container of the radio inputs double in width when a red input is checked and makes it original width when a yellow input is checked. In the original width container the red inputs are over the yellow ones, but in the double width container, the red inputs are moved away.
Recognizing patterns
In real life, the Connect 4 board does not tell you if you have won or lost, but providing proper feedback is part of good user experience in any software. The next objective is to detect whether a player has won the game. To win the game a player has to have four of their discs in a column, row or diagonal line. This is a very simple task to solve in many programming languages, but in pure CSS world, this is a huge challenge. Breaking it down to subtasks is the way to approach this systematically.
I used a flex container as the parent of the radio buttons and discs. A yellow radio button, a red radio button and a div for the disc belong to a slot. Such a slot is repeated 42 times and arranged in columns that wrap. Consequently, the slots in a column are adjacent, which makes recognizing four in a column the easiest part using the adjacent selector:
<div class="grid">
<input type="radio" name="slot11">
<input type="radio" name="slot11">
<div class="disc"></div>
<input type="radio" name="slot12">
<input type="radio" name="slot12">
<div class="disc"></div>
...
<input type="radio" name="slot16">
<input type="radio" name="slot16">
<div class="disc"></div>

<input type="radio" name="slot21">
<input type="radio" name="slot21">
<div class="disc"></div>
...
</div>
/* Red four in a column selector */
input:checked + .disc + input + input:checked + .disc + input + input:checked + .disc + input + input:checked ~ .outcome

/* Yellow four in a column selector */
input:checked + input + .disc + input:checked + input + .disc + input:checked + input + .disc + input:checked ~ .outcome
This is a simple but ugly solution. There are 11 type and class selectors chained together per player to cover the case of four in a column. Adding a div with class of .outcome after the elements of the slots makes it possible to conditionally display the outcome message. There is also a problem with falsely detecting four in a column where the column is wrapped, but let's just put this issue aside.
A similar approach for detecting four in a row would be truly a terrible idea. There would be 56 selectors chained together per player (if I did the math right), not to mention that they would have a similar flaw of false detection. This is a situation where the :nth-child(An+B [of S]) or the column combinators will come handy in the future.
For better semantics one could add a new div for each column and arrange the slot elements in them. This modification would also eliminate the possibility of false detection mentioned above. Then detecting four in a row could go like: select a column where the first red radio input is checked, and select the adjacent sibling column where the first red radio input is checked, and so on two more times. This sounds very cumbersome and would require the "parent" selector.
Selecting the parent is not feasible, but selecting the child is. How would detecting four in a row go with available combinators and selectors? Select a column, then select its first red radio input if checked, and select the adjacent column, then select its first red radio input if checked, and so on two more times. It still sounds cumbersome, yet possible. The trick is not only in the CSS but also in the HTML, the next column has to be the sibling of the radio buttons in the previous column creating a nested structure.
<div class="grid column">
<input type="radio" name="slot11">
<input type="radio" name="slot11">
<div class="disc"></div>
...
<input type="radio" name="slot16">
<input type="radio" name="slot16">
<div class="disc"></div>

<div class="column">
<input type="radio" name="slot21">
<input type="radio" name="slot21">
<div class="disc"></div>
...
<input type="radio" name="slot26">
<input type="radio" name="slot26">
<div class="disc"></div>

<div class="column">
...
</div>
</div>
</div>
/* Red four in a row selectors */
input:nth-of-type(2):checked ~ .column > input:nth-of-type(2):checked ~ .column > input:nth-of-type(2):checked ~ .column > input:nth-of-type(2):checked ~ .column::after,
input:nth-of-type(4):checked ~ .column > input:nth-of-type(4):checked ~ .column > input:nth-of-type(4):checked ~ .column > input:nth-of-type(4):checked ~ .column::after,
...
input:nth-of-type(12):checked ~ .column > input:nth-of-type(12):checked ~ .column > input:nth-of-type(12):checked ~ .column > input:nth-of-type(12):checked ~ .column::after
Well the semantics are messed up and these selectors are only for the red player (another round goes for the yellow player), on the other hand it does work. A little benefit is that there will be no falsely detected columns or rows. The display mechanism of the outcome also had to be modified, using the ::after pseudo element of any matching column is a consistent solution when proper styling is applied. As a result of this, a fake eighth column has to be added after the last slot.
As seen in the code snippet above, specific positions within a column are matched to detect four in a row. The very same technique can be used for detecting four in a diagonal by adjusting these positions. Note that the diagonals can are in two directions.
input:nth-of-type(2):checked ~ .column > input:nth-of-type(4):checked ~ .column > input:nth-of-type(6):checked ~ .column > input:nth-of-type(8):checked ~ .column::after,
input:nth-of-type(4):checked ~ .column > input:nth-of-type(6):checked ~ .column > input:nth-of-type(8):checked ~ .column > input:nth-of-type(10):checked ~ .column::after,
...
input:nth-of-type(12):checked ~ .column > input:nth-of-type(10):checked ~ .column > input:nth-of-type(8):checked ~ .column > input:nth-of-type(6):checked ~ .column::after
The number of selectors have increased vastly in the final run, and this is definitely a place where CSS preprocessors could reduce the length of the declaration. Still, I think the demo is moderately short. It should be somewhere around the middle on the scale from hardcoding a selector for every possible winning pattern to using 4 magical selectors (column, row, two diagonals).
A message is shown when a player wins
Closing loopholes
Any software has edge cases and they need to be handled. The possible outcomes of a Connect 4 game are not only the red, or yellow player winning, but neither player winning filling the board known as draw. Technically this case doesn't break the game or produce any errors, what's missing is the feedback to the players.
The goal is to detect when there are 42 :checked radio buttons on the board. This also means that none of them are in the :indeterminate state. That is requiring a selection to be made for each radio group. Radio buttons are invalid, when they are :indeterminate, otherwise they are valid. So I added the required attribute for each input, then used the :valid pseudo-class on the form to detect draw.
The draw outcome message is shown when the board is filled
Covering the draw outcome introduced a bug. In the very rare case of the yellow player winning on last turn, both the win and draw messages are displayed. This is because the detection and display method of these outcomes are orthogonal. I worked around the issue by making sure that the win message has a white background and is over the draw message. I also had to delay the fade in transition of the draw message, so it would not get blended with the win message transition.
The yellow wins message is over the draw outcome preventing it to be displayed
While a lot of radio buttons are hid behind each other by absolute positioning, all of those in indeterminate state can still be accessed by tabbing through the controls. This enables players to drop theirs discs into arbitrary slots. A way to handle this is to simply forbid keyboard interactions by the tabindex attribute: setting it to -1 means that it should not be reachable via sequential keyboard navigation. I had to augment every radio input with this attribute to eliminate this loophole.
<input type="radio" name="slot11" tabindex="-1" required>
<input type="radio" name="slot11" tabindex="-1" required>
<div class="disc"></div>
...
Limitations
The most substantial drawback is that the board isn't responsive and it might malfunction on small viewports due to the unreliable solution of tracking turns. I didn't dare to take the risk of refactoring to a responsive solution, due to the nature of the implementation it feels much safer with hardcoded dimensions.
Another issue is the sticky hover on touch devices. Adding some interaction media queries to the right places is the easiest way to cure this, though it would eliminate the free fall animation.
One might think that the :indeterminate pseudo-class is already widely supported, and it is. The problem is that it is only partially supported in some browsers. Observe Note 1 in the compatibility table: MS IE and Edge do not support it on radio buttons. If you view the demo in those browsers your cursor will turn into the not-allowed cursor on the board, this is an unintentional but somewhat graceful degradation.
Not all browsers support :indeterminate on radio buttons
Conclusion
Thanks for making it to the last section! Let's see some numbers:

140 HTML elements
350 (reasonable) lines of CSS
0 JavaScript
0 external resources

Overall, I'm satisfied with the result and the feedback was great. I sure learned a lot making this demo and I hope I could share a lot writing this article!

How the Roman Empire Made Pure CSS Connect 4 Possible is a post from CSS-Tricks
Source: CssTricks


Font of the Month Club

Every month for the past year, David Jonathan Ross has been publishing a new font to his Font of the Month Club. It’s only $6 for a monthly subscription and it provides early access to some of his work. I’d highly recommend signing up because each design is weird and intriguing in a very good way:

Join the Font of the Month Club and get a fresh new font delivered to your inbox every single month! Each font is lovingly designed and produced by me, David Jonathan Ross.
Fonts of the month are not available anywhere else, and will include my distinctive display faces, experimental designs, and exclusive previews of upcoming retail typeface families.

Direct Link to Article — Permalink
Font of the Month Club is a post from CSS-Tricks
Source: CssTricks


The Front-End Checklist is just a tool… everything depends on you.

One month ago, I launched the Front-End Checklist on GitHub. In less than 2 weeks, more than 10,000 people around the world starred the repository. That was completely unexpected and incredible!

I've been working as a front-end developer since 2011, but I started to build websites in 2000. Since then, like us all, I've been trying to improve the quality of my code and deliver websites faster. Along the way, I've been managing developers from two different countries. That has helped me to produce a checklist a little different than what I've found on around the web over the years.
While I was creating the checklist, I continuously had the book "The Checklist Manifesto: How to Get Things Right" by Atul Gawade in mind. That book has helped me build checklists for my work and personal life, and simplify things that sometimes seem too complex.

amzn_assoc_tracking_id = "csstricks-20";
amzn_assoc_ad_mode = "manual";
amzn_assoc_ad_type = "smart";
amzn_assoc_marketplace = "amazon";
amzn_assoc_region = "US";
amzn_assoc_design = "enhanced_links";
amzn_assoc_asins = "0312430000";
amzn_assoc_placement = "adunit";
amzn_assoc_linkid = "bc96260be7adede1459bf758a120d189";

If you are working alone or in a team, individually, remotely, or on-site, I wanted to share some advice on using the Front-End Checklist and the web application that goes with it. Perhaps I can convince you to integrate it into your integrationcycle.
#1 Decide which rules your project and team need to follow
Every project is different. Before starting a new project, the whole team (i.e. the project managers, designers, developers, QA, etc.) need to agree on what the deliverables will be.
To help you to decide, I created 3 different levels of priority: high, medium, and low. You don't necessarily need to agree with those distinctions, but they may help order your tasks.
The Front-End Checklist app was done to facilitate the creation of personalized checklists. Change some JSON files to your liking and you are ready to start!
#2 Define the rules to check at beginning, during, and at the end of your project
You shouldn't check all these rules only at the end of a project. You know as well as I do how projects are at the very end! Too hectic. Most of the items of the Front-End Checklist can be considered at the beginning of your development. It's up to you to decide. Make it clear to your team upfront what happens when.
#3 Learn a little more about each rules
Who loves reading the docs? Not most of us, but it's essential. If you want to understand the reasons for the rule, you can't avoid reading up about them. The more you understand the why of each rule, the better developer you become.
#4 Start to check!
The Front-End Checklist app can facilitate your life as a developer. It's a live checklist, so as you complete items your progress and grade are updated live. Everything is saved in localStorage so you can leave and come back as needed.
The project is open source, so feel free to fork it and use it however you like. I'm working on making sure all the files are commented. I especially invite those interested in Pug to take a look at the views folder.

#5 Integrate automated testing in your workflow
We all dream of automation (or is it just me?). For now, the Front-End Checklist is just an interactive list, but some of the tasks can be automated in your workflow.
Take a look at the gulpfile used to generate the project. All tasks are packages you can use with npm, webpack, etc.
#6 Validate every pages before sending to QA team and to production

If you're passionate about generating clean code and care about your code quality, you should be regularly testing your pages. It's so easy to make mistakes and remove some essential code. Or, someone else on your team might have done it, but it's your shared responsibilty to be catching things like that.
The Front-End Checklist can generate beautiful reports you can send to a project manager or Quality Assurance team.
#7 Enjoy your work above all
Some people might look at such a long checklist and feel sick to their stomach. Going through such a list might cause anxiety and really not be any fun.
But the Front-End Checklist is just a tool to help you deliver higher quality code. Code that affects all aspects of a project: the SEO, the user experience, the ROI, and ultimately the success of the project. A tool that can help across all those things might actually help reduce your anxiety and improve your health!
Conclusion
The success the Front-End Checklist received in such a short time reminded me that a lot of people are really interested in finding ways to improve their work. But just because the tool exists doesn't directly help with that. You also need to commit to using it.
In a time where AI is taking over many manual tasks, quality is a must-have. Even if automation takes over a lot of our tasks, some level of quality will remain impossible to automate, and us front-end developers still have many long days to enjoy our jobs.

The Front-End Checklist is just a tool… everything depends on you. is a post from CSS-Tricks
Source: CssTricks


​7 Days of Free Stock Images

(This is a sponsored post.)Storyblocks is exploding with over 400,000 stock photos, vectors, backgrounds and more! With its user friendly site, massive library to choose from, and fresh new content, there’s no stopping what you can do. All of the content is 100% free from any royalties. Anything you download is yours to keep and use forever! Right now you can get 7 days of free downloads. Get up to 20 photos, icons, and vectors everyday for 7 days. That's 140 downloads free over the course of the 7 days. Click on over and see where your imagination takes you! Start downloading now.

Direct Link to Article — Permalink
​7 Days of Free Stock Images is a post from CSS-Tricks
Source: CssTricks


Localisation and Translation on the Web

The other day Chris wrote about how the CodePen team added lang='en' to the html element in all pens for accessibility reasons and I thought it was pretty interesting but I suddenly wanted to learn more about that attribute because I’ve never designed a website in any other language besides English and it might be useful for the future.
As if by magic Ire Aderinokun published this piece on Localisation and Translation on the Web just a couple of days later and thankfully it answers all those questions I had:

Coming from the English-speaking world, it can be easy to maintain the bubble that is the English-speaking World Wide Web. But in fact, more than half of web pages are written in languages other than English.
Since starting work at eyeo, I’ve had to think a lot more about localisation and translations because most of our websites are translated into several languages, something I previously didn’t have to really consider before. Once you decide to translate a web page, there are many things to take into account, and a lot of them I've found are useful even if your website is written in only one language.

I had no idea about the experimental, and currently unsupported, translate attribute or the mysterious margin-inline-start CSS property. Handy stuff!
Direct Link to Article — Permalink
Localisation and Translation on the Web is a post from CSS-Tricks
Source: CssTricks


Fontastic Web Performance

In this talk Monica Dinculescu takes a deep dive into webfonts and how the font-display CSS property lets us control the way those fonts are rendered. She argues that there’s all sorts of huge performance gains to be had if we just spend a little bit of time thinking about the total number of fonts we load and how they’re loaded.
Also, Monica made a handy demo that gives an even more detailed series of examples of how the font-display property works:

This depends a lot on how you are using your webfont, and whether rendering the text in a fallback font makes sense. For example, if you're rendering the main body text on a site, you should use font-display:optional. On browsers that implement it, like Chrome, the experience will be much nicer: your users will get fast content, and if the web font download takes too long, they won't get a page relayout halfway through reading your article.
If you're using a web font for icons, there is no acceptable fallback font you can render these icons in (unless you're using emoji or something), so your only option is to completely block until the font is ready, with font-display:block.

Direct Link to Article — Permalink
Fontastic Web Performance is a post from CSS-Tricks
Source: CssTricks