Archiwum kategorii: CSS

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 ArticlePermalink


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

Guetzli

Post pobrano z: Guetzli

Geutzili, Google’s new open source algorithm…

…that creates high-quality JPEG images with file sizes 35% smaller than currently available methods, enabling webmasters to create webpages that can load faster and use even less data.

I’ve seen this fairly widely reported, and that’s great because images are the main cause of web bloat these days and fighting back with tech seems smart.

I also saw Anselm Hannemann note:

This is great, but to put things into perspective, we also have to consider that it’s up to 100 times slower as Mozilla’s mozJPEG encoder and in many cases, it doesn’t achieve the same quality at the same file size

Source: Kornel Lesiński, the guy behind ImageOptim, who says Guetzli will be incorporated into the next version.

Direct Link to ArticlePermalink


Guetzli is a post from CSS-Tricks

Text Effects with CSS (and a little contenteditable trick)

Post pobrano z: Text Effects with CSS (and a little contenteditable trick)

Mandy Michael has been creating some incredible text effects with just the power of CSS. She uses every trick in the book: gradients, transforms, pseudo elements, shadows, and clipping paths to name a few. They are all real web text too. Custom fonts typically, but no images, canvas, or SVG or anything like that.

Take a look at this beautiful effect:

See the Pen CSS only 3D paper fold text effect by Mandy Michael (@mandymichael) on CodePen.

The fact that it is real text makes it accessible, searchable, and of course, selectable:

Demos are an awesome place to use the contenteditable attribute, which turns any text element into sort of like a textarea or input, in that then anyone can click right into it and change the text.

<h1 contenteditable>Cool Title</h1>

But because many of Mandy’s demos use pseudo elements with text that needs to match the text in the element itself, the text can get out-of-sync:

Never fear! It’s just a few lines of JavaScript to keep those bits of text in sync:

var h1 = document.querySelector("h1");

h1.addEventListener("input", function() {
  this.setAttribute("data-heading", this.innerText);
});

The input event is real handy, as it covers any change in an element’s value, even contenteditable elements. It has decent browser support, just no IE (Edge is fine). If you really needed this for IE, you could still get it done combining events like keyup, paste, and blur and stuff. But you probably don’t need to for a little thing like this.

Now we’re all good:

But before we go, let’s bask in more of Mandy’s creations:

See the Pen Lines and layered css text effects by Mandy Michael (@mandymichael) on CodePen.

See the Pen Stripy Rainbow Text Effect by Mandy Michael (@mandymichael) on CodePen.

See the Pen Single element, multi coloured 3d text effect by Mandy Michael (@mandymichael) on CodePen.

See the Pen Split fractured text by Mandy Michael (@mandymichael) on CodePen.


Text Effects with CSS (and a little contenteditable trick) is a post from CSS-Tricks

Zeroing the Desk

Post pobrano z: Zeroing the Desk

Brendan Dawes:

After a recording session on one of those large mixing desks, after you’ve twiddled countless knobs and push around many faders you do something called zeroing the desk. This is were you turn every control and push every fader back to zero, so that when the next engineer comes in he or she isn’t going to jump out of their seat when a large sub-bass whacks them straight in the face and possibly blows something up. It’s a polite thing to do for your fellow sound engineer.

Reminds me of all: unset; 😉

(via Brad Frost)

Direct Link to ArticlePermalink


Zeroing the Desk is a post from CSS-Tricks

The Next Smashing Magazine

Post pobrano z: The Next Smashing Magazine

Congrats to the big team over there assembled to take on this major redesign process. Unlike our redesigns around here that are usually more like realignments with minor dev work and UX sprinkles each iteration, this was a ground-up rebuild for them. They migrated a bunch of different platforms all into one, a static-site based system with all front end APIs. It’s gotta feel good to pull all that stuff into one system. I remember when I used to have four different systems around here (WordPress, Forums (various), eCommerce (various), and some raw PHP stuff) and the good feeling it was to get it all yanked in under one WordPress roof.

Direct Link to ArticlePermalink


The Next Smashing Magazine is a post from CSS-Tricks