Archiwum kategorii: CSS

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 Article — Permalink


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 Article — Permalink


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

Lazy Loading Gravatars in WordPress

Post pobrano z: Lazy Loading Gravatars in WordPress

Most WordPress themes show user Gravatars in the comment threads. It’s a way of showing an image with the user, as associated by the email address used. It’s a nice touch, and almost an expected design pattern these days.

Every one of those gravatars is an individual HTTP request though, like any other image. A comment thread with 50 comments means 50 HTTP requests, and they aren’t always particularly tiny files. Yeesh.

Let’s lazy load them.

The Concept

Lazy loading is the idea that you don’t even request the image at all (no HTTP request) unless the image is visible. Meaning that, through JavaScript, we’ve determined the image is visible.

Lazy loading means not loading those two images that are outside the browser window, until they become inside the browser window.

In order to stop those HTTP requests for not-yet-seen images, we need to get our hands directly on the markup. If there is an <img src=""> in the HTML, there is essentially no way to stop the browser from downloading that image as soon as it possibly can, seen or unseen. So, we need to remove that src, and put it back when we’re ready.

Woah, There

It’s worth a pause here because we’ve entered some murky territory.

By removing the src of these images, and only ever putting it back with JavaScript, we’ve decided that we’re willing to ship slightly invalid HTML and rely 100% on a script downloading and executing for these images to ever be seen.

I’m OK with that. Mostly because gravatars are just an enhancement anyway. It ain’t no big deal if they never show up. I’m not a hardliner most JavaScript debates, but this seems like a particularly clear case where we can lean on JavaScript without worry.

Altering the HTML

This is the change we’d be making:

<!-- Normal image. No beating the browser preloader. -->
<img src="https://gravatar.whatever..." alt="" />

<!-- Let's change to this, which won't download anything. -->
<img data-src="https://gravatar.whatever..." alt="" />

Although a missing src on the <img> is technically invalid HTML. It almost certainly doesn’t really matter in that it won’t affect how anything works. If the invalid HTML bugs, you could always toss a super minimal blank GIF data URL in there, like:

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" ... />

Using width and height attributes is probably a good idea too, to maintain layout and avoid reflow if and when the images to load.

Altering the HTML… in WordPress

But how do you change the HTML that WordPress spits out as part of a comment thread? Comments are slightly unusual in WordPress in that WordPress core gives you the HTML, it isn’t part of your theme like most of the other HTML is.

Likely, in your `comments.php` file, you’ll see this function:

<?php wp_list_comments(); ?>

Which spits out a pile of <li>’s with your entire comment thread. Not a lot of opportunity there to be fiddling with the output of images. Except, we can! We can list a callback function in there:

<?php wp_list_comments('callback=csstricks_comment'); ?>

That callback is the name of a function we can toss in our `functions.php` file. Here’s an example of that function, which must return a <li>:

function csstricks_comment($comment, $args, $depth) {

  $GLOBALS['comment'] = $comment; ?>

  <li <?php comment_class(); ?>">

     <img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="50" height="50" class="lazyload-gravatar" alt="User Avatar" data-src="<?php echo get_avatar_url(get_comment_author_email($comment_ID), array("size" => 160)); ?>">

     <?php comment_text(); ?>

  <?php # phantom </li> ?>

<?php }

That’s very simplified, but you can see what we’ve done. We replaced the src with the blank GIF, we’ve added a class name we’ll ultimately use in JavaScript to do the lazy loading, we’ve added a data-src to the actual gravatar, and we’re using width and height attributes for placeholding. Here’s my actual complete callback live right now on CSS-Tricks.

If we shipped this right now, sans any JavaScript work, we’d still have a perfectly functional comment thread, just with images that never load.

Now We’re Ready to Lazyload

The hard part is over. We’re perfectly set up to do lazyloading now. If we were to write a script, it would be like:

  1. Figure out the visible area of the browser window
  2. Figure out the position on the page of every image with class .lazyload-gravatar
  3. If any of those images are in the visible area, flop out the src with the value from data-src
  4. If the visible area of the browser window changes in any way, re-evaluate the above

We could set about writing that ourselves. And we could do it! But, and I’m sure you’re not surprised here, it’s a bit tricky and nuanced. Cross-browser concerns, performance concerns, does-it-work-on-mobile concerns, to name a few. This is the kind of thing I’m happy to lean on other’s work for, rather than roll myself.

Again, no surprise, there are loads of options to pick from. In my case, I’m happily using jQuery on CSS-Tricks, and I picked a jQuery-based on that looked pretty good to me:

The API is as simple as can be. After bundled up the lib with the rest of the libs I’m using, I just call:

$('.lazyload-gravatar').Lazy();

Look how nicely it works!

That’s an awful lot of saved HTTP requests and awful good for performance.

Makes you wish web standards and browsers would get together on this and make it a native feature.


Lazy Loading Gravatars in WordPress is a post from CSS-Tricks

Building a CSS Grid Overlay

Post pobrano z: Building a CSS Grid Overlay

Let’s take a look at what it takes to build a grid overlay with CSS. It will be responsive, easily customizable and make heavy use of CSS variables (known more accurately as „CSS custom properties”). If you aren’t familiar with custom properties, I’d highly recommend reading What is the difference between CSS variables and preprocessor variables? and watching Lea Verou’s enlighting talk on using them.

This grid overlay that we’re building will consider a developer tool, as in, a tool just for us, not really our users. So, let’s not worry too much about browser support (If you do care, check out caniuse… data on custom properties). While it’s impossible to preprocess custom properties to behave exactly the same as native support, if you use them just like you would preprocessor variables, tools like the postCSS plugin cssnext can transform them into CSS compliant with older browsers.

Preface

A couple of weeks ago, at work, I simplified the media queries on one of our projects and added a layout component based on the same principles as Flexbox Grid. Some of my fellow designers didn’t fully understand the responsiveness and fluidity of it, so I created a toggleable grid overlay to help them visualize it.

My hope is that this can be a tool to aid layout-related conversations on our teams and make sure we don’t use too many bespoke widths, paddings etc.

Terminology

Working as a front end designer I want all developers and designers to speak the same language (as much as possible) so I’ve chosen a terminology for the CSS variables that digital designers are also familiar with:

  • Columns: The vertical divisions of the page.
  • Gutter: The space between the columns.
  • Offset: The space between the sides of the viewport.
  • Baseline: The vertical rhythm used for text.

Making the Grid

1) „Box”

Let’s use a pseudo-element on the element to display the grid on top of all of our content. We want the overlay to work with a fluid layout, so we give the element a width off `100% – (2 * offset)` and also a max-width so the grid overlay doesn’t grow wider than our layout.

See the Pen

2) Columns

If you look at the grid you will notice that the repeating pattern is column+gutter pairs. We’re using repeating linear gradients as a background-image. We’ll set the size of the background-image to 100% + gutter making the repeating pattern 100% / columns wide and the actual column (100% / columns) – gutter wide.

See the Pen

As a side note, I also tried using regular linear gradients with background-repeat to get the lines more pixel perfect. It didn’t work because pixel rounding resulted in imperfect total width whenever the layout width wasn’t dividable by the number of columns.

3) Baseline

We also draw the baseline using repeating linear gradients but it’s slightly simpler since we don’t add horizontal gutters and we want it to be just a line instead of a block.

Let’s also add a baseline-shift variable that allows us to shift the baseline slightly upwards or downwards. We apply the baseline shift by simply adjusting the background-position.

See the Pen

4) Media Queries

Now that we have our basic setup, let’s introduce some media queries. If you look back at the math that we’ve used so far, you can see that none of it is tied up to any specific number of columns, gutter width, etc.

We use a mobile first approach and only include variables in the media queries when we want to change them. To make it clear for everyone using the overlay that we’ve passed a new breakpoint we also change the color at every breakpoint.

I recommend opening the Pen in a new tab and see how it behaves when you change different variable values and when you resize the viewport.

See the Pen

If you made a mental note in step 1 saying “but what if I want specific layout widths at specific breakpoints?” then now is when you can easily introduce that logic by setting --max_width for each media query.

5) Help Text

Designers like to think about mockups for different devices — which is generally a good thing as it’s critical that a website looks awesome on those different devices — but sometimes they forget that the layout on an iPad should work all the way up and/or down to the next breakpoint.

Breakpoints aren’t normally called „iPhone”, „Galaxy Note 🔥”, „iPad” etc. for many reasons including the above. A breakpoint denotes where a new range starts and it’s not device specific.

To make it more obvious what our breakpoints are called, we can add the names to our grid overlay.

See the Pen

I have a dream that one day a designer doesn’t come back to a developer and say: „we need to adjust how it looks on iPad” but instead says „we need to adjust how it looks on medium”.

Go Further

What about lines for the columns and gutters too? Easy, it’s just CSS. What about adding more breakpoints? Easy, it’s just CSS. What if I want different colors? Easy… you get it. 😄

You can see a more advanced example here:

See the Pen

I’d love to get your input either here or on the GitHub repository which also includes a Chrome extension using this approach.


Building a CSS Grid Overlay is a post from CSS-Tricks

Recreating Legendary 8-bit Games Music with the Web Audio API

Post pobrano z: Recreating Legendary 8-bit Games Music with the Web Audio API

Greg Hovanesyan, who recently posted here an Introduction to the Web Audio API, follows up with another huge post on how to use it to create iconic music from our nerds past, like sounds from The Legend of Zelda and Metroid.

The final demo comes as a project you can explore. And don’t miss our recent roundup of some of the best Web Audio API Pens ever on CodePen.

Direct Link to Article — Permalink


Recreating Legendary 8-bit Games Music with the Web Audio API is a post from CSS-Tricks

Slides: CSS-Tricks is a Poster Child WordPress Site

Post pobrano z: Slides: CSS-Tricks is a Poster Child WordPress Site

I just gave a talk at WordCamp Miami where I talked about, to some degree, how WordPress has been a great choice for CSS-Tricks over the last decade.

If I get a chance I’ll try to re-give the talk to my computer locally here so there will be a way you can watch the talk with some real context.


Slides: CSS-Tricks is a Poster Child WordPress Site is a post from CSS-Tricks

Using DevTools to Tweak Designs in the Browser

Post pobrano z: Using DevTools to Tweak Designs in the Browser

Let’s look at some ways we can use the browsers DevTools to do design work. There are a few somewhat hidden tricks you mind find handy!

Toggling Classes With Checkboxes

This is useful when trying to pick a design from different options or to toggle the active state of an element without adding the class manually in DevTools.

To achieve this, we could use different classes and scope styles inside them. So if we want to see different options for a banner design, we could so something like:

.banner-1 {
  /* Style variation */
}

.banner-2 {
  /* Style variation */
}

Google Chrome gives us the ability to add all of these classes and toggle (show/hide) them with a checkbox to make a quick comparison between them.

See the demo Pen.

Editing Content with designMode

Web content is dynamic, so our design should be flexible and we should test for various types and lengths of content. For example, entering a very long word might break a design. To check that, we can edit our design right in the browser with document.designMode.

This can help us test our design without editing the content manually in the source code.

Hiding Elements

Sometimes we need to hide elements in our design to check how it will look without them. Chrome DevTools give us the ability to inspect an element and type h from the keyboard to hide it by toggling CSS visibility property.

This is very useful in case you want to hide some elements to take a screenshot and then discuss it with your team/designer/manager. Sometimes I use this feature to hide elements and then take a screenshot to mock a quick idea in Photoshop.

Screenshotting design elements

There is a useful feature in Firefox DevTools to take a screenshot of a specific element in the DOM. By doing that, we can compare our variations side by side to see which one is the best of our case.

Follow the below steps:

  1. Open Firefox DevTools
  2. Right-click on an element and pick Screenshot Node
  3. The screenshots are saved in the default downloads folder

If you want to use Chrome for screenshotting, you can. There is a plugin called „Element Screenshot” that does almost the same job.

Changing Design Colors

In the early stages of every design projects, you might be exploring different color palettes. CSS’ hue-rotate function is a powerful filter that provides us with the ability to change design colors right in the browser. It causes hue rotation for each pixel in an image or element. The value can be specified in deg or rad.

In the below video, I added filter: hue-rotate(value) to the component, notice how all the colors change.

Notice that every design element got affected from applying hue-rotate. For example, the user avatar colors looks wrong. We can revert the normal look by applying the negative value of hue-rotate.

.bio__avatar {
  filter: hue-rotate(-100deg);
}

See the demo Pen.

Using CSS Variables (Custom CSS Properties)

Even if the support is still not perfectly cross-browser friendly (it’s currently in development in Microsoft Edge), we can get the benefit of CSS variables today. Using them to define the spacing and color units will make it easy to make huge changes by changing tiny values on the fly.

I defined the following for our web page:

:root {
  --spacing-unit: 1em;
  --spacing-unit-half: calc(var(--spacing-unit) / 2); /* = 0.5em */
  --brand-color-primary: #7ebdc2;
  --brand-color-secondary: #468e94;
}

These variables will be used throughout the website elements like links, nav items, borders and background colors. When changing a single variable from the dev tools, all the associated elements will be affected!

Invert elements with CSS filter: invert()

This is useful when you have a white text on black background or vice versa. For instance, in the header, we have the page title in white on a black background, and by adding filter: invert to the element, all the colors will be inverted.

CSS Visual Editor

This feature is becoming better every day. Safari has really nice UI tools for editing values. Chrome is adding similar things slowly to DevTools.

Chrome has some cool stuff for things like box-shadow, background-color, text-shadow and color.

I think this will be very useful for designers who doesn’t know much about CSS. Editing things visually like that will give them more control over some design details, they can tweak things in the browser and show the result to the developer to be implemented.


Using DevTools to Tweak Designs in the Browser is a post from CSS-Tricks