Archiwum kategorii: CSS

Focusing a `background-image` on a Precise Location with Percentages

Post pobrano z: Focusing a `background-image` on a Precise Location with Percentages

Let’s say you have an element with a background-image, where only part of the image is visible, because the image is bigger than the element itself. The rest is cropped away, outside the element.

Now you want to move that background-image such that you’re focusing the center of the element on a specific point in it. You also want to do that with percentage values rather than pixels. We’re going to have to get clever.

This is going to involve some math.

Let’s use this as our image, which has markers for sizing:

And here’s our element, with that background-image applied. Notice we can only see the (top) left of the image:

See the Pen Background Focus: no position by Jay (@jsit) on CodePen.

Now let’s say we want to align a specific point on the image with the center of that element. Say, the point at 300px in from the left.

Since we’re asking for this position in pixels, it’s straightforward. With no position defined, the background-image „starts” with the point at 100 pixels at the center, so you need to move it to the left by 200 pixels:

See the Pen Background Focus: pixel position by Jay (@jsit) on CodePen.

Let’s formalize it.

The x value you’re using for background-position is calculated like so:

(0.5 × [bounding box width]) - [x-coordinate]
             0.5 × 200px -              300px
                   100px -              300px = -200px

It takes a second to figure out, but it’s nothing too taxing. You could have probably figured that out intuitively without needing to use a formula.

But what if you wanted to (or had to) express background-position as a percentage? Shouldn’t be too hard, right? Let’s try using a percentage to get ourselves centered at 300px again. We had a background-position-x of -200px, so let’s convert that to percent: -200 / 800 = -25%, so:

See the Pen Background Focus: percentage (1st attempt) by Jay (@jsit) on CodePen.

Hm. That didn’t work at all. Maybe we need to use a positive value?

See the Pen Background Focus: percentage (2nd attempt) by Jay (@jsit) on CodePen.

That’s better, but it’s centered at, like… 250px? How about as a percentage of the bounding box width: 300 / 200 = 150%. That can’t be right…

See the Pen Background Focus: percentage (3rd attempt) by Jay (@jsit) on CodePen.

Yeah, that’s not right.

Let’s back up. What happens if we do this?

See the Pen Background Focus: percentage (4th attempt) by Jay (@jsit) on CodePen.

That feels like it kind of makes sense; background-position: 100% 0; makes the background-image flush-right and centered at 700px, or 7/8 the width of the image. But what if we wanted to center it at 100%? I guess we’d have to do… 9/8?

See the Pen Background Focus: percentage (5th attempt) by Jay (@jsit) on CodePen.

At this point, I’m not surprised that didn’t work.

This doesn’t feel like the right path. Let’s back up.

What does the spec say?

For example, with a value pair of '0% 0%’, the upper left corner of the image is aligned with the upper left corner of, usually, the box’s padding edge. A value pair of ‘100% 100%’ places the lower right corner of the image in the lower right corner of the area. With a value pair of '75% 50%’, the point 75% across and 50% down the image is to be placed at the point 75% across and 50% down the area.

Maybe we can reverse-engineer this.

On that last one, 112.5%, it was aligning the point at 112.5% across the background-image with the point at 112.5% across the bounding box. That kind makes sense. The spec seems written to make it easy for only three values: 0%, 50%, and 100%. Any other value isn’t so intuitive.

With background-position: 0;, we were focused on 100px, or 12.5%. With background-position: 100% 0;, we were focused on 700px, or 87.5%. How does background-position: 50% 0; look, exactly?

See the Pen Background Focus: percentage (6th attempt) by Jay (@jsit) on CodePen.

50% is kind of like our „anchor” here; it’s the point at which our desired focal point and the corresponding background-position values are equal.

Let’s pretend we want to focus on 700px or 87.5%. We go 100% of the way from the center: 50% + 50%.

See the Pen Background Focus: percentage (4th attempt) by Jay (@jsit) on CodePen.

With background-position set to 100%, the center of our bonding box has „panned” from the center of the image, 3/4 of the way to the rightmost edge (from 400px to 700px). If we want to „pan” to the rightmost edge, we need to go that extra 1/4, or 200px. 1/4 is 1/3 of 3/4, so we need to go a third more than we did a moment ago, or a total of 66.667% from the center:

See the Pen Background Focus: percentage (7th attempt) by Jay (@jsit) on CodePen.

Whew! So to focus on the rightmost edge of a background-image that is 4 times the size of our bounding box, we need to set background-position: 116.667% 0;.

How the heck are we supposed to figure that out?

It’s a difference of 16.667% from the 100% we might expect. So if we wanted to focus on our original goal of 300px (or, 37.5%), we’d, uh, add 16.667%? There’s no way this is going to work:

See the Pen Background Focus: percentage (8th attempt) by Jay (@jsit) on CodePen.

Nope.

If we wanted to focus on the leftmost edge, we’d probably subtract 16.667% from 0%, right? That sounds like it could be right.

See the Pen Background Focus: percentage (9th attempt) by Jay (@jsit) on CodePen.

Cool!

To focus at 100% or 0%, you have to „overshoot” those values by a certain amount, when measured from the center.

So if we want to focus on 0%, or „100% of the way to the left of the center,” we have to subtract 66.667% from 50%. If we want to focus on 100%, or „100% of the way to the right of the center,” we have to add 66.667% to 50%.

I might have expected to have to add or subtract 50% to or from 50% to get to those edges: a 1:1 ratio of „how far I want to go from the center” to „what my background-position value should be.” But instead, we have to use a 4:3 ratio. In other words, we have to use a value four-thirds more „away from the center.”

Things are getting a little hairy here, so let’s introduce some terms:

  • c: Desired focal point (in percent) from leftmost edge of background image
  • z: Zoom factor (background width ÷ bounding box width)
  • p: background-position, to focus on c, given z

So we take a focal point’s distance from the center (c − 50), multiply it by 4/3, then add that result to „the center,” or 50.

If you wanted to focus on the point at 600px (or 75%), my background-position value should be:

(75% − 50%) × 4/3 + 50% = 83.333%

Yes, that sounds like it could work! Please please please:

See the Pen Background Focus: percentage (10th attempt) by Jay (@jsit) on CodePen.

Awesome!

And if you wanted to focus on 200px, or 25%, you would do:

(25% − 50%) × 4/3 + 50% = 16.667%

See the Pen Background Focus: percentage (11th attempt) by Jay (@jsit) on CodePen.

Wow.

Let’s generalize this:

(c − 50%) × 4/3 + 50% = p

So why 4/3? 4 is the ratio of our background-image width to our bounding box width; and 3 is… 1 less than 4. Could it be that simple? Let’s try a larger background-image, this time 1000px wide, or 5 times the width of our bounding box. And let’s again try to focus on the point at 200px. Here our equation would be:

(20% − 50%) × 5/4 + 50% = 12.5%

See the Pen Background Focus: percentage (12th attempt) by Jay (@jsit) on CodePen.

Oh my god. It works!

So to revisit our equation, with a variable background-to-bounding-box ratio:

(c − 50%) × z/(z − 1) + 50% = p

Let’s turn this into English:

Given a point on a background-image at location c…

  1. with c expressed as a percentage of the width of the image
  2. where c is intended to lie in the horizontal center of the background image’s bounding box
  3. and where the background-image is z times as wide as its bounding box

the correct background-position p (expressed as a percentage) is given by the following formula:

(c − 50%) × z/(z − 1) + 50% = p

Can we generalize this even more?

What if we wanted to align the point at 25% of the background-image with the point at 75% of the bounding box? Yikes!

Let’s revisit our original formula:

(c − 50%) × z/(z − 1) + 50% = p

Now let’s introduce some new terms:

  • b: Desired focal point (in percent) from the leftmost edge of the bounding box. Earlier we had assumed this to always be 50% so that the center of the bounding box would be focused on our target in the background-image.
  • d: background-image focal point (in percent) to align to bounding box’s midpoint in order to get c to align to b in the bounding box; if d of the background-image aligns with 50% of the bounding box, then c of the background-image will align with b of the bounding box.

Let’s think of it this way

To want to align position c of a background-image with position b of a bounding box is to want to align some other position, d, of a background-image with the center of the bounding box – and we already know how to do that. So can we figure out a way to derive d, the spot we need to be at 50%, from c, b, and z? Sure!

With our 800px wide background-image, in a 200px-wide bounding box (z = 4), if we want to focus the rightmost edge of the bounding box (b = 100%) on the position at 600px (c = 75%) in the image, we would want the center of the bounding box to be focused on the point at 500px (d = 62.5%).

How do we get from c (75%) to d (62.5%)? Where does that -12.5% difference come from?

Well, our b was 100%, 50% greater than our old „default” b of 50%. And 12.5% is 1/4 of that; 1/4 is the inverse of our z of 4. Is that where our d comes from? That would be:

d = c + (50% - b)/z

Looks promising. Now we can substitute d in for c in the original formula:

(d − 50%) × z/(z − 1) + 50% = p

Or:

(c + (50% − b)/z - 50%) × z/(z − 1) + 50% = p

Whew! Let’s test this. Let’s try to align the position at 25% in our background-image (200px) with the position at 75% in our bounding box. This would be:

p = (25% + (50% - 75%)/4 - 50%) × 4/(4 - 1) + 50%
p = -31.25% × 1.333 + 50%
p = 8.333%

See the Pen Background Focus: percentage (13th attempt) by Jay (@jsit) on CodePen.

Unbelievable! Let’s double check. How about the point at 87.5% in our background-image (700px) aligned with the position at 33.333% in our bounding box:

p = (87.5% + (50% - 33.333%)/4 - 50%) × 4/(4 - 1) + 50%
p = 41.6667% × 1.333 + 50%
p = 105.555%

See the Pen Background Focus: percentage (14th attempt) by Jay (@jsit) on CodePen.

Looks good enough to me!

I’m sure there is something intuitive about this to certain types of people, but I am not one of those people.

Let’s build a Sass function that will do all this ridiculous math for us.

See the Pen Background Focus: percentage (final Sass function) by Jay (@jsit) on CodePen.

My head is spinning.

When I began tackling this problem I did not expect it to be this difficult, but what a journey. I hope guiding you through my thought process has been enlightening, and that you may at some point find value in our little Sass function.

All the Pens embedded in this article can be found in this collection.


Focusing a `background-image` on a Precise Location with Percentages is a post from CSS-Tricks

Photicular

Post pobrano z: Photicular

I was on vacation this past week and at some little beach gift shop they were selling this really cool big thick book called Ocean: A Photicular Book. You’ve probably seen something like it before… a plastic card that shows different images depending on how you are looking at it. This book is extremely well done in that the image are very high quality, and the design of the book makes the images move as you turn the pages.

Here’s a quick video:

check this book it's the coolest pic.twitter.com/isRLATp9im

— Chris Coyier (@chriscoyier) April 13, 2017

Here’s an explanation by Dan Kainen:

Photicular, also known as Lenticular, or Integrated Photography, was first conceived in the early 20th century, but the basic concept has been around since 1692 when a French painter created paintings that revealed one, and then the other as the observer walked by. The simplest form of it is to cut two images into thin vertical strips and interleave them, placing in front of the composite image a plane of bars, like a picket fence, which only allows one to see one image at a time through the gaps. Instead of bars, lenses can be used, and more than two images – as many as dozens – can be interleaved.

The end result is really neat in the Ocean book. After mentioning this one on Twitter, I’ve heard good things about the Safari one as well. I’m sure they are all awesome. It’s almost like the newspapers and paintings in Harry Potter!

Of course, it made me think about how we might do something Photicular-like on the web. We have videos and GIFs on the web, so it’s not exactly hard to make images move. But it’s not just in the movement itself that made these books cool, it was that it moves along with your actions (of turning the page).

Perhaps we could page through a GIF as a user scrolled. Can you programmatically control which frame of GIF is currently being shown? Sorrrrrrta. There is no simple native technology for that, but there are some alternatives.

Dennis Gaebel wrote about a technique he saw on the Capser Mattress site last year.

Rather than a GIF, you can use an image sprite, and swap out which part of the image you are showing as you scroll. His final demo is here:

See the Pen How to Animate a Coffee Drinking Sprite With ScrollMagic by Envato Tuts+ (@tutsplus) on CodePen.

If you really wanted to stick with a GIF, BuzzFeed actually created a JavaScript library called libgif-js specifically for exerting control over GIFs in this way. Through this lib, you can jump to certain frames, pause and start the GIF like you can with video, and even make the GIFs „rubbable”, meaning dragging left-and-right on them scrub the GIF backward and forwards.

To get super meta, here’s a GIF of me playing with a „rubbable” GIF:

The squishing is just what the GIF is of, it’s the ability to scrub through the GIFs frames that is interesting here. Well, squishing Steve Buscemi’s head is interesting too, but you know what I mean.

Related

A decade ago, I remember my old boss Tim Chatman designing a paper flip book thing for a client of ours.

It’s not Photicular, but it uses the same kind of slotted paper tabs you pull to make the images change.

I’m also reminded of one of my own favorite childhood books, Dinnertime, where different animals pop out at you as you turn the pages.


Photicular is a post from CSS-Tricks

ES6 modules support lands in browsers: is it time to rethink bundling?

Post pobrano z: ES6 modules support lands in browsers: is it time to rethink bundling?

Modules, as in, this kind of syntax right in JavaScript:

import { myCounter, someOtherThing } from 'utilities';

Which we’d normally use Webpack to bundle, but now is supported in Safari Technology Preview, Firefox Nightly (flag), and Edge.

It’s designed to support progressive enhancement, as you can safely link to a bundled version and a non-bundled version without having browsers download both.

Stefan Judis shows:

<!-- in case ES6 modules are supported -->
<script src="app/index.js" type="module"></script>
<!-- in case ES6 modules aren't supported -->
<script src="dist/bundle.js" defer nomodule></script>

Not bundling means simpler build processes, which is great, but forgoing all the other cool stuff a tool like Webpack can do, like „tree shaking”. Also, all those imports are individual HTTP requests, which may not be as big of a deal in HTTP/2, but still isn’t great:

Khan Academy discovered the same thing a while ago when experimenting with HTTP/2. The idea of shipping smaller files is great to guarantee perfect cache hit ratios, but at the end, it’s always a tradeoff and it’s depending on several factors. For a large code base splitting the code into several chunks (a vendor and an app bundle) makes sense, but shipping thousands of tiny files that can’t be compressed properly is not the right approach.

Preprocessing build steps are likely here to stay. Native tech can learn from them, but we might as well leverage what both are good at.

Direct Link to ArticlePermalink


ES6 modules support lands in browsers: is it time to rethink bundling? is a post from CSS-Tricks

Between the Lines

Post pobrano z: Between the Lines

Media queries are great for changing values in sudden snaps at different screen sizes. But, combining the power of calc() and viewport units like vw and vh , we can get an awful lot of fluidity across our layouts. For this we’ll use a technique called linear interpolation.

Linear interpolation is a formula used to find a value between two points on a line. In our case those two points are CSS values, like font-sizes, margins or widths, that we want to interpolate between over a set of viewport widths.

The reason we might want to interpolate between values over a set of viewport widths is to avoid having to create multiple breakpoints to control the flow of our content when the viewport changes. Instead, we let the user’s browser calculate, according to our instructions, what values it gets. Let me explain.

The following snippet is a Sass function based on linear interpolation that we, at Aranja, have been calling between.

/**
 * Computes a CSS calc function that betweens a value from
 * A to B over viewport-width A to viewport-width B.
 * Requires a media query to cap the value at B.
 */

@function between($to, $from, $toWidth, $fromWidth) {
  $slope: ($to - $from) / ($toWidth - $fromWidth);
  $base: $from - $slope * $fromWidth;

  @return calc(#{$base} + #{100vw * $slope});
}

The function is used like so:

$small: 400px; 
$large: 1000px;

.Container {
  /* The base (smallest) value. */
  padding: 20px;

  /* In $small it should be 20px and in $large it should be 100px,  */
  /* In viewports between that its padding should be calculated */
  @media (min-width: $small) {
    padding: between(20px, 100px, $small, $large);
  }

/* In $large we cap the value at 100px */
  @media (min-width: $large) {
    padding: 100px;
  }
}

The code example above shows how we can between a container’s padding from being 20px in “mobile”-size to being 100px in “desktop”-size. Any size between that would get a calculated amount of padding ranging between 20 and 100 pixels. To prevent the padding from exceeding the maximum value we cap it with a breakpoint.

Try resizing the following demo to see the example in action:

See the Pen

The between function excels in solving spacing problems. Problems that previously we would have solved by hand using different media queries.

Example layout

The talented Carly Sylvester lent me the following wireframe she designed for a volunteer firefighter website so I get to demonstrate this technique on a real-world layout.

The design document consists of a desktop, tablet and mobile versions of the website, at 1440px, 720px and 324px respectively.
In reality, the lines between these different devices are not so clear-cut, so we’ll use the given values as target points and interpolate between them using our function.

Notice how the layout of the desktop and tablet versions are similar except for the use of white-space and font-sizes–which we’ll be able to interpolate between smoothly. When we get to our smallest target point we snap the layout into a classic full-width mobile layout.

See the Pen

For comparison, let’s see the implementation done the usual way, where the 3 main breakpoints are used to snap the layout their new values.

See the Pen

Videos of Demos

Resizing layout with between
Resizing layout without between

Try browsing the demos in different screen sizes and the benefits of our function should be clear. To make the „regular” version of the website better we’d need to add more breakpoints in addition to the original three from the design document, resulting in more jumps.

Combined with the power of rem

A powerful technique we can do with the function is to between the root font-size and base our styles on rems:

See the Pen

The rem unit refers to the root font-size (the font size set on the :root or html element) to determine its value and the root font-size refers to the viewport width to determine its value. We set the root font-size to be 10px at the smallest and 18px at the largest and the result is a smooth transition between the two. The smallest the card in the demo ever gets is 245px, at our $small breakpoint, and it gradually grows until it reaches its peak, 440px, at our $large breakpoint.

Closing

I am convinced that by utilizing this technique we can make the web a better experience for users browsing on devices that don’t fit into the generalization of „mobile” or „tablet” sizes. For me, at least, it also makes the development process more enjoyable as there are fewer layout-related bugs on my table.

Regarding browser support–the fact that we only need calc() and vw for the technique to work puts it at around 97% in USA and Europe, and around 84% globally.

In the demos above, for example, unsupported browsers (Which are mainly Opera Mini and UC Browser) will either use our lowest (base) values or our highest (capped) values, depending on the viewport width.


Between the Lines is a post from CSS-Tricks

Let’s Define Exactly What Atomic CSS is

Post pobrano z: Let’s Define Exactly What Atomic CSS is

As Atomic CSS (also known as Functional CSS) has been gaining in popularity, some confusion has occurred about similar related terms. The goal of this article is to clarify this terminology.

There are other projects that use the term Atomic, including Atomic Web Design by Brad Frost. Atomic CSS is a completely separate concept from these.

Let’s start by defining Atomic CSS:

Atomic CSS is the approach to CSS architecture that favors small, single-purpose classes with names based on visual function.

There are different ways to write Atomic CSS (see variations below). One example would be this:

.bgr-blue { 
  background-color: #357edd; 
}

The term „Atomic CSS” was coined by Thierry Koblenz in his foundational article „Challenging CSS Best Practices” in October 2013.

Some people started referring to this approach as „Functional CSS” some time later. Though there have been cases in the past where Functional CSS has been used to describe something else, today the terms Functional CSS and Atomic CSS are used interchangeably.

While Atomic CSS has been the title of an open source project which originated with Thierry’s original article, the term itself applies to the architectural philosophy, not any one particular variation (see below).

Variations of Atomic CSS

Static

Many people write Atomic CSS much like they have always written CSS. It is common to use a preprocessor to generate a library of classes with set variations that define a unit-based design system for spacing, color, typography, etc.

The advantage to this style is that because it is familiar, it has a lower barrier to entry, and is more easily understood by those who are not well-versed in CSS.

Programmatic

The Programmatic approach to Atomic CSS involves using a build tool to automatically generate styles based on what it finds in the HTML.

For example, given this:

<!-- Programmatic Atomic CSS Example -->
<div class="Bgc(#0280ae) C(#fff) P(20px)">
    Lorem ipsum
</div>

The following CSS would be generated:

.Bgc\(#0280ae\) { background-color: #0280ae; }
.C\(#fff\) { color: #fff; }
.P\(20px\) { padding: 20px; }

This flavor of Atomic CSS uses the syntax of a function call with parameters. As demonstrated by the open source ACSS project, which uses Atomizer to programmatically generate styles, it is no longer necessary to write CSS whatsoever. Stylesheets that are generated during the build process are fully optimized with no unused styles of any sort.

Longhand/Shorthand

The longhand style favors more readable class names (see Expressive CSS and Solid), while shorthand favors brevity (see Tachyons and Basscss).

/* Shorthand Atomic CSS Examples */

.bg-blue { background-color: #357edd; } 
.f1 { font-size: 3rem; }
.ma0 { margin: 0; }

/* Longhand Atomic CSS Examples */

.bgr-blue { background-color: #357edd; }
.background-blue  { background-color: #357edd; }
.backgroundcolor-blue  { background-color: #357edd; }
.text-h1 { font-size: 3rem; }
.text-3rem { font-size: 3rem; }
.text-huge { font-size: 3rem; }
.fontsize-1 { font-size: 3rem; }
.marg-0 { margin: 0; }
.margin-0 { margin: 0; }

/* Programmatic Shorthand */

Bgc(#357edd) { background-color: #357edd; }

/* Programmatic Longhand */

bgrBlue(#357edd) { background-color: #357edd; }
backgroundBlue(#357edd) { background-color: #357edd; }
backgroundColorBlue(#357edd) { background-color: #357edd; }

Related Terms

Utility Classes

Utility classes (also referred to as Helper Classes) are easily understood, single function classes that help with common styling patterns (e.g. .clearfix, .hidden).

Many CSS architectures rely on utility classes (e.g. grids, spacing, typography) but do not necessarily fully embrace the concept of Atomic CSS.

Immutable CSS

An aspect of Atomic/Functional CSS where utility classes are never to be modified, thus producing highly dependable results.

Immutability plays an essential role in the proper execution of Atomic CSS architecture. Without it, you risk this:

.black {color:navy;}

Atomic CSS is about shifting complexity away from stylesheets and into HTML. When design changes occur in a Atomic CSS project, it is best if you have well-structured HTML templates so that, for example, you can use an editing tool to quickly change Bgc(colorOne) to Bgc(colorTwo) wherever you may need to.

Breakpoint Prefixing

This technique is a way to allow utility classes to override styles at different breakpoints to make implementation of responsive web design simple and efficient.

/* Examples of breakpoint prefixing */

.grid-12   /* Full width by default */
.m-grid-6  /* 2 column at medium screen sizes */
.l-grid-4  /* 3 column for large screen sizes */

Getting Started

Below is a list of places you can go to begin, depending on which variation you prefer.

Additionally, here are some foundational articles that are worth reading:

„In The Wild”

Atomic CSS has gained in popularity particularly among those who use it for rapid prototyping and, on the other end of the spectrum, for large scale ongoing front end projects.


Thank you to Thierry Koblenz for his feedback on this article and hard work over the years!


Let’s Define Exactly What Atomic CSS is is a post from CSS-Tricks

Papercons

Post pobrano z: Papercons

Bobby Grace, on the Dropbox Paper team:

On the engineering side, we use inline SVGs. These have many advantages. One advantage is that SVG is a well-structured format that we can manipulate with code. Paper is also using React and has a component for inserting icons.

They:

  1. Use a single Sketch file, checked into the repo, as the place to design and house all the icons.
  2. Use gulp-sketch to extract them all individually.
  3. The build script continues by optimizing them all and building a source of data with all the icons and their properties.
  4. That data fuels the their <SvgIcon /> React component. (Also see our article).

They call it Papercons.

Now, whenever someone asks for an icon, we can just share a link to all the latest production icons. No more hunting, context switching, and long conversation threads.

Direct Link to ArticlePermalink


Papercons is a post from CSS-Tricks

Debugging Tips and Tricks

Post pobrano z: Debugging Tips and Tricks

Writing code is only one small piece of being a developer. In order to be efficient and capable at our jobs, we must also excel at debugging. When I dedicate some time to learning new debugging skills, I often find I can move much quicker, and add more value to the teams I work on. I have a few tips and tricks I rely on pretty heavily and found that I give the same advice again and again during workshops, so here’s a compilation of some of them, as well as some from the community. We’ll start with some core tenants and then drill down to more specific examples.

Main Concepts

Isolate the Problem

Isolation is possibly the strongest core tenant in all of debugging. Our codebases can be sprawling, with different libraries, frameworks, and they can include many contributors, even people who aren’t working on the project anymore. Isolating the problem helps us slowly whittle away non-essential parts of the problem so that we can singularly focus on a solution.

Some of the benefits of isolation include, but are not limited to:

  • Figuring out if it’s actually the root cause we think it is or some sort of conflict
  • For time-based tasks, understanding whether or not there is a race condition
  • Taking a hard look at whether or not our code can be simplified, which can help with both writing it and maintaining it
  • Untangling it and seeing if it’s one issue or perhaps more

It’s very important to make the issue reproducible. Without being able to discern exactly what the issue is in a way where you can reproduce it, it’s very difficult to solve for it. This also allows you to compare it to working model that is similar so that you can see what changed or what is different between the two.

I have a lot of different methods of isolation in practice. One is to create a reduced test case on a local instance, or a private CodePen, or a JSBin. Another is to create breakpoints in the code so that I can see it execute bit by bit. There are a few ways to define breakpoints:

You can literally write debugger; inline in your code. You can see how this will fire small pieces at a time.

You can take this one step further in Chrome DevTools and even walk through the next events that are fired or choose specific event listeners:

Step into the next function call

Good 'ol console.log is a form of isolation. (Or echo in PHP, or print in python, etc…). You are taking one tiny piece of execution and testing your assumptions, or checking to see if something is altering. This is probably the most time-tested form of debugging, that no matter how advanced you become, still has it’s uses. Arrow functions in ES6 have allowed us to step up our console debugging game as well, as it’s now a lot easier to write useful one-liners in the console.

The console.table function is also a favorite tool of mine, especially great for when you have a lot of data you need to represent- large arrays, large objects and the like. The console.dir function is also a nice alternative. It will log an interactive listing of an object’s properties.

console.dir gives an interactive listing

Be Methodical

When I teach workshops and help students in my class, the number one thing that I find holds them back as they try to debug a problem is not being methodical enough. This is truly a tortoise-and-the-hare kind of situation. They understandably want to move quickly, so they change a ton of things at once, and then when something stops working, they don’t know which thing they changed is causing the error. Then, to debug, they change many things at once and get a little lost trying to figure out what is working and what isn’t.

We all do this to some extent. As we become more proficient with a tool, we can write more and more code without testing an assumption. But if you’re new to a syntax or technology, being slow and careful behooves you. You have a much better shot at backing out of an issue you might have inadvertently created for yourself. And indeed, once you have created an issue, debugging one thing at a time might seem slower, but exposes exactly what changes have happened and where the error lies in a way that a seemingly faster pace doesn’t allow. I say seemingly because the time isn’t actually recovered working this way.

Do you remember when you were a kid and your parents said, „if you get lost, stay where you are?” My parents did, at least. It’s because if they were moving around to find me and I was also moving around to find them, we’d have fewer chances of bumping into one another. Code works the same way. The less moving pieces you have, the better- the more you are returning consistent results, the easier it will be to track things down. So while you’re debugging, try not to also install anything, or put in new dependencies. If you see a different error every time you should be returning a static result, that’s a big red flag you should be headed right for with your sleuth hat on.

Choose Good Tools

There are a million different tools for solving a variety of problems. I’m going to work through some of the tools I find the most useful and then we’ll link off to a bevy of resources.

Syntax Highlighting

Sure, it’s damn fun to pick out the new hotness in colors and flavors for your syntax highlighting theme, but spending some time thinking about clarity here matters. I often pick dark themes where a skip in syntax will turn all of my code a lighter color, I find errors are really easy to see right away. I tend to like Oceanic Next or Panda, but really, to each their own on this one. It’s important to keep in mind that when looking for a good syntax highlighter, awesome-looking is great, but functional for calling out your mistakes is most important, and it’s totally possible to do both.

Linting

Linting helps flag suspicious code and calls out errors we might have overlooked. Linting is incredibly important, but which linter you choose has so much to do with what language/framework you’re writing in, and then on top of that, what your agreed-upon code style is.

Different companies have different code styles and rules. Personally, I like AirBnB’s, but take care and don’t just use any old linter. Your linter enforces patterns that, if you yourself don’t want to enforce, can stall your build process. I had a CSS linter that complained whenever I wrote a browser hack, and ended up having to circumvent it so often that it stopped being useful. But a good linter can shine light on small errors you might have missed that are lurking.
Here are some resources:

Browser Extensions

Extensions can be really awesome because they can be enabled and disabled so readily, and they can work with really specific requirements. If you’re working with a particular library or framework, chances are, having their extension for DevTools enabled is going to give you all sorts of clarity that you can’t find otherwise. Take care though- not only can extensions bog a browser down, but they have permissions to execute scripts, so do a little homework into the extension author, ratings, and background. All that said, here are some of my favorites:

  • Accessibility extension from Dequeue Systems
  • React DevTools really vital, in my opinion, if you’re working with React, to see their virtual DOM
  • Vue DevTools same endorsement as above.
  • Codopen: pops you out of the editor mode into a debug window for CodePen. Full disclosure: my husband made this for me as a present because he was sick of watching me manually opening the debug window (best gift ever!)
  • Pageruler: get pixel dimensions and measure anything on a page. I like this one because I’m super duper anal about my layout. This helps me feed the beast.

DevTools

This is probably the most obvious of debugging tools, and there are so many things you can do with them. They can have so many packed-in features that can be easy to miss, so in the next section of specific tips, we’ll go into a deep dive of some favorites.

Umar Hansa has great materials for learning what the DevTools can do. He has a weekly newsletter and GIFs, a new course linked in the last section, and an article on our site.

One of my favorite recent ones is this CSS Tracker Enhancement, shown here with permission from Umar. This shows all of the unused CSS so that you can understand the performance impact.

The CSS tracker shows color-coded rules for used and unused sets.

Misc Tools

  • What input is a global utility for tracking the current input method (mouse, keyboard or touch), as well as the current intent- this can be really good for tracking down accessiblity leaks (hat tip to Marcy Sutton, accessibility expert for this tipoff)
  • Ghostlabapp is a pretty snazzy tool if you’re doing responsive development or checking anything deployed across a ton of devices. It offers synchronized web development, testing, and inspection.
  • Eruda is an awesome tool that helps debug on mobile devices. I really like it because it takes a simulator a step further, gives a console and real devtools to help you gain understanding.
eruda gives you a mobile console

Specific Tips

I am always interested in what other people do to debug, so I asked the community through the CSS-Tricks account and my own what they were really into. This list is a mixture of tips I like as well as a roundup of tips from the community.

Accessibility

$('body').on('focusin', function() {
  console.log(document.activeElement);
});

This logs the currently focused element, useful because opening the Devtools blurs the activeElement

Marcy Sutton

Debugging CSS

We got quite a lot of responses saying that people put red borders on elements to see what they’re doing

@sarah_edo for CSS, I'll usually have a .debug class with a red border that I slap on troublesome elements.

— Jeremy Wagner (@malchata) March 15, 2017

I do this too, I even have a little CSS file that drops in some classes I can access for different colors easily.

Checking State in React

@sarah_edo <pre>{JSON.stringify(this.state, null, 2)}</pre>

— MICHAEL JACKSON (@mjackson) March 15, 2017

Props to Michael, this is one of the most useful debugging tools I know of. That snippet „pretty prints” the state of the component you’re working with onto the component so that you can see what’s going on. You can validate that the state is working the way that you think it should be, and it helps track down any errors between the state and how you’re using it.

Animation

We got a lot of responses that said they slow the animation way down:

@sarah_edo @Real_CSS_Tricks * { animation-duration: 10s !important; }

— Thomas Fuchs (@thomasfuchs) March 15, 2017

I mentioned this on a post I wrote right here on CSS Tricks about debugging CSS Keyframe animations, there are more tips too, like how to hardware accelerate, or work with multiple transforms in different percentages.

I also slow down my animations in JavaScript- in GreenSock that would look like: timeline.timeScale(0.5) (you can slow down the whole timeline, not just one thing at a time, which is super useful), in mo.js that would look like {speed: 0.5}.

Val Head has a great screencast going through both chrome and firefox devtools offering on animation.

If you want to use the Chrome Devtools timeline to do performance audits, it’s worth mentioning that painting is the most expense of the tasks, so all things being equal, pay a little more attention to a high percentage of that green.

Checking different connection speeds and loads

I tend to work on fast connections, so I will throttle my connection to check and see what the performance would look like for people who don’t have my internet speed.

throttle connection in devtools

This is also useful in conjunction with a hard reload, or with the cache empty

@sarah_edo Not so secret trick. But still many people are unaware. You need DevTools open, and then right click over the refresh button. pic.twitter.com/FdAfF9Xtxm

— David Corbacho (@dcorbacho) March 15, 2017

Set a Timed Debugger

This one came from Chris. We have a whole writeup on it right here:

setTimeout(function() {
  debugger;
}, 3000);

It’s similar to the debugger; tool I mentioned earlier, except you can put it in a setTimeout function and get even more fine-tuned information

Simulators

@Real_CSS_Tricks And just in case any Mac users didn't know this, iOS simulator + Safari is sweet. pic.twitter.com/Uz4XO3e6uD

— Chris Coyier (@chriscoyier) March 15, 2017

I mentioned simulators with Eruda before. iOS users also get a pretty sweet simulator. I was going to tell you you have to install XCode first, but this tweet showed another way:

@chriscoyier @Real_CSS_Tricks Or, you can use this approach if you didn't want to bother with installing xCode: https://t.co/WtAnZNo718

— Chris Harrison (@cdharrison) March 15, 2017

Chrome also has a device toggle which is helpful.

Remote Debuggers

@chriscoyier @Real_CSS_Tricks https://t.co/q3OfWKNlUo is a good tool.

— Gilles 💾⚽ (@gfra54) March 15, 2017

I actually didn’t know about this tool until seeing this tweet. Pretty useful!

CSS Grid Debugging

Rachel Andrew gave a presentation at Smashing and mentioned a little waffle thing you can click on in Firefox that will illuminate the gutters in the grid. Her video explains it really eloquently.

Rachel Andrew shows how to highlight gutters in Firefox DevTools.

Array Debugging

Wes Bos with a really useful tip for searching for a single item in an array:

If you are just looking for a single item array.find() is 🔥 https://t.co/AuRtyFwnq7

— Wes Bos (@wesbos) March 15, 2017

Further Debugging Resources

Jon Kuperman has a Frontend Masters course that can help you master devtools it goes along with this app.

There’s a small course on code school called discover devtools.

Umar Hansa has a new online course called Modern DevTools.

Julia Evans has a great article about debugging here, hat tip to Jamison Dance for showing it to me.

Paul Irish does some advanced performance audits with devtools if you’re super nerdy like me and want to dig into the timeline.

Finally, I’ll put in a bittersweet resource. My friend James Golick who was an excellent programmer and even more excellent human gave this great conference talk about debugging anything many years ago. Sadly James has passed, but we can still honor his memory and learn from him:


Debugging Tips and Tricks is a post from CSS-Tricks

Strangers in the Woods Together

Post pobrano z: Strangers in the Woods Together

In the latest episode of ShopTalk, Robyn Kanner told a story of interviewing for a UX job that stuck with me.

They asked her to create a social app for mountain bikers. Talk out how the app might work, sketch out some flows, you know, UX work. Exactly what they were expecting and what I would have done. But then Robyn turned the table on them and asked what they are going to do about saftey. This app is going to allow strangers to connect and meet in the woods together, how can you ensure their safety?

Geez. Seems obvious after she says it, but at the outset of the question it didn’t seem so obvious. At least to a dude like me. As Mike Monterio put it, we’re both big dudes who don’t think twice about getting into a Lyft with strangers, but is top of mind for plenty of others. There are huge blind spots like this that affect our work.

Direct Link to ArticlePermalink


Strangers in the Woods Together is a post from CSS-Tricks

How To Make Guides (Collections of Content) in WordPress

Post pobrano z: How To Make Guides (Collections of Content) in WordPress

A blog post can be anything you want. You could easily write one that links up a bunch of articles on your site. Titles, summaries, links… all hand-crafted HTML. A „guide”, as it were. It will likely be appreciated by your readers, I find, especially when you’re linking up old evergreen content that is still relevant and useful today.

But let’s say you want to programmatically create these „guides”. That might make them faster to create, easier to maintain, and give you a nice level of control over them. Let’s look at a way to do that.

Guides on CSS-Tricks

I’m writing about this because guides are something we’ve just started to do here on CSS-Tricks. For example, I wanted to make a guide of our content that is well suited for folks just starting out, so I made Our Guide To Just Starting Out with CSS & HTML.

That wasn’t built by hand, it was built by programmatically attaching a variety of content to a Custom Post Type we created just for Guides.

Programmatically Attaching Posts to Posts

You know how you can put images into blog posts? But in WordPress, there is also a concept of a featured image, which is one specific programmatically attached image for that post.

That image is programatically attached to this Post.

Enabling that feature in WordPress is like:

add_theme_support('post-thumbnails', array('post', 'page', 'whatever'));

But we’re talking associating Posts with Posts not Images to Posts. There is no built-in WordPress way of doing that, so we’ll reach for plugins.

CMB2 and Friends

CMB2 (i.e. the second version of „Custom Meta Boxes”) is a free, open source plugin for adding better UI and functionality around custom fields. If you’re familiar with Advanced Custom Fields, it’s a bit like that, only I guess entirely free and a bit more modular.

With that installed, now you can install (I guess we’ll call them sub-plugins?) that make CMB2 do stuff. The one we’re after is CMB2 Attached Posts Field which has the explicit job of attaching Posts to Posts (or really, post type to any post type).

It gives you this two-column UI on post types you activate it for:

Move anything from the left to right, and it’s now programatically attached. This is exactly what we’re after. Now we can hand select, and hand order, any type of post to attach to any other.

Configuring Things

Before you get to the UI you can see above, you not only need to install and activate those two plugins, but also tell CMB2 to create the custom meta boxes and apply them to the types of posts you want.

In our case, our Guides are a custom post type. That’s easy enough to enable:

register_post_type( 'guides',
  array(
    'labels'        => array(
      'name'          => __( 'Guides' ),
      'singular_name' => __( 'Guide' ),
      'add_new'       => __( 'Add Guide' ),
      'add_new_item'  => __( 'Add New Guide' ),
      'edit_item'     => __( 'Edit Guide' ),
    ),
    'public'      => true,
    'has_archive' => true,
    'rewrite'     => array( 'slug' => 'guides' ),
    'supports'    => array( 'title', 'editor', 'thumbnail', 'excerpt' )
  )
);

Then we apply this new custom meta box only to that custom post type (so we don’t have to see it everywhere):

$cmb = new_cmb2_box( array(
  'id'            => 'guide_metabox',
  'title'         => __( 'The Guide Metabox', 'cmb2' ),
  'object_types'  => array( 'guides', ), // Post type
  'context'       => 'normal',
  'priority'      => 'high',
  'show_names'    => true, // Show field names on the left
  // 'cmb_styles' => false, // false to disable the CMB stylesheet
  // 'closed'     => true, // Keep the metabox closed by default
) );

// Regular text field
$cmb->add_field( array(
  'name'       => __( 'Things for the Guide', 'cmb2' ),
  'id'         => 'attached_cmb2_attached_posts',
  'type'       => 'custom_attached_posts',
  'show_on_cb' => 'cmb2_hide_if_no_cats',
  'options' => array(
    'show_thumbnails' => true, // Show thumbnails on the left
    'filter_boxes'    => true, // Show a text box for filtering the results
    'query_args'      => array(
      // 'posts_per_page' => 2,
      'post_type' => array('post', 'page')
    ), // override the get_posts args
  ),
) );

We nestle all this code nicely into a functionality plugin, rather than a `functions.php` file, so that changing themes has no bearing on this content.

A Template for Guides

Now that a custom post type exists for our guides, adding a file called `single-guides.php` into our active theme is enough to make that the file that renders for like `/guide/example/`.

In that file, we do whatever normal template-y stuff we’d do on any other template file (e.g. `page.php`, but also loop through all these posts we’ve attached!

<?php

  $attached = get_post_meta(get_the_ID(), 'attached_cmb2_attached_posts', true);

  foreach ($attached as $attached_post) {
    $post = get_post($attached_post); ?>

  <?php include("parts/article-card.php"); ?>

<?php } ?>

All in all, not that much to it!

It feels great to have some kind of mechanism for surfacing evergreen content like this. That can be quite a challenge for sites with a huge amount of content!


High five to Rebekah Monson, whom I ripped this idea off of, who uses this to build guides on The New Tropic, like these neighborhood guides.


How To Make Guides (Collections of Content) in WordPress is a post from CSS-Tricks

`matrix3d()` for a Frame-Perfect Custom Scrollbar

Post pobrano z: `matrix3d()` for a Frame-Perfect Custom Scrollbar

Das Surma:

In this article we will leverage some unconventional CSS matrices to build a custom scroller that doesn’t require any JavaScript while scrolling, just some setup code.

If turning a scrollbar into a Nyan cat with near-perfect functionality isn’t a CSS trick, I don’t know what is.

Direct Link to ArticlePermalink


`matrix3d()` for a Frame-Perfect Custom Scrollbar is a post from CSS-Tricks