Archiwum kategorii: CSS

2017 Staff Favorites

Post pobrano z: 2017 Staff Favorites

It’s been a very productive year for the web community, and as all of us here at CSS-Tricks roamed around to conferences, read posts, and built projects, there were some highlights of contributions that really stuck out to us. Each of us picked 5 resources that were either the most helpful, the most unique, or are things you might have missed that we think are worth checking out.

Sarah’s Picks

The Miracle of Generators

I quite like when someone takes a deep dive on a particular subject and does it well. I had the honor of seeing Bodil Stokke give this talk at Frontend Conference Zurich and it’s as charming and entertaining as it is educational.

Designing with Grid

Jen Simmons covers the status of CSS Grid, and how to work with it from design to development. Jen is a master of grid, and the lab section of her site shows the capability of this medium.

An update since this talk has come out: Grid has also shipped in Microsoft Edge.

Vue Apollo

This is more like two things I’m interested in wrapped up in a single thing. Guillaume Chau has done a great job of creating an Apollo/GraphQL integration for Vue, including a few great demos to explore.

The Coding Train

This resource has been out for a while, but Dan now has such a great collection that it’s a great time to mention it.

Coding Train are small, half-hour chunks of tutorials- everything from creating a star field to learning how Neural Networks work. Dan is an incredibly engaging and lovable instructor and makes you feel very welcome when exploring new concepts.

Motion in Design Systems

Val Head gets to the heart of the matter when it comes to integrating motion into a Design System or Component Library.

It can be really tough to communicate animation because you necessarily need to collaborate between design and engineering. Val gives you some tools to make this process function well.

Robin’s Picks

Design Systems

Design Systems by Alla Kholmatova was one of the best design books I read in 2017.

It’s a book all about how to collaborate with a team and reveals that code quality is only one part of designing great systems on the web. The book isn’t so much about design as much as it’s about learning how to communicate across large groups of people and how we can better communicate with everyone in an organization.

Web Typography

Another great book I read this year was Web Typography by Richard Rutter, this time focusing a great deal more on the relationship between CSS and typesetting.

My favorite part of the book though is where Richard describes that web typography is fundamentally different from other forms of typesetting and requires a series of new skills. It makes for exciting reading.

Purple.pm

For most of this year I’ve been focusing on improving my UX and product design skills and I have to say that Purple was the most useful tool for organizing large amounts of data and research. I used it as an archive that stored every document I made, every Balsamiq wireframe and hi-fi Figma mockup I created all in one place. This made it so much easier to communicate with other teams and explain my thinking on a project.

Figma

This year I switched to using the web-based design tool Figma full time. It’s been so very useful because my day job work requires collaborating with dozens of engineers, product managers and other designers — so being able to quickly share a mockup with them and get feedback has exponentially improved my design chops. Plus, it reminds me of Fireworks which is probably one of the best apps ever made.

Inkwell

This year Hoefler & Co. released Inkwell, a new family of typefaces that mimics a variety of handwriting styles and I can’t stop thinking about them. One great example of their use is on Chris’ blog where all these weird styles shouldn’t work at all but somehow they just do.

Chris’ Picks

A Design System for All Americans by Mina Markham

A masterclass in public speaking if you ask me. Funny, personal, and right on target for the kind of work a lot of us are doing.

Notion

Notion is probably the most significant bit of new software I’ve switched to this year. It’s a notes app at it’s core and it’s feature-rich in that regard. One of my favorites features is that every note is also a folder, so you can get as nested as you like with your organization. If you give it a shot, I bet you’ll be able to see how it quickly can replace lots of other apps.

Most significant to a list like this, is that it’s built for the web, but also has native apps on a variety of platforms. I think 2017 was significant in that we started to really feel a blurring between what is web and what is platform native. I suspect it will get harder and hard to tell, and then with all the advantages the web has inherently, it will make less and less sense to build anywhere else.

CSS

CSS had a banner year. CSS Grid, of course, but we also got font-display starting to ship, which is wonderful for performance. We got landmark selectors like :focus-within that prove parent selectors aren’t impossible. Vector graphics has moved it way into CSS with a collection of properties, including animation and movement. You might say CSS has gotten more capable and easier. I enjoyed writing posts like this one about a slider that shows how far you can get in CSS these days.

RIP Firebug

I think it’s nice the Firebug homepage is an homage, goodbye, and short history to Firebug. Firebug laid the foundation for what good DevTools could be. I’m glad browsers have taken them in-house and turned them into the powerhouses we use now, but that’s all thanks to Firebug.

If I had to pick the most significant three things that have made the web the development platform it is today: 1) DevTooling, started by Firebug 2) The agreement from all browsers that web standards benefit everyone and actually being disciplined about applying that thinking 3) Evergreen browsers.

PWAs

I feel like Progressive Web Apps are essentially good marketing for a collection of good ideas that benefit any website. That’s exactly the case Jason Grigsby makes:

That makes it an easy pick for 2017. HTTPS! Service workers for offline friendliness! Performance focused! Do these things, and be rewarded with more features that native apps enjoy, like a position on the home screen on mobile devices. Blur them lines, y’all! Even if you don’t do everything on the list, there are big advantages for every step along the way.

Geoff’s Picks

CSS Grid

This one comes as no surprise but it’s certainly worthy of multiple mentions. Grid has really rejuvenated my love for CSS. Not only does it take a lot of the complexity of out layouts that used to require creative uses of floats, displays and positioning, but it has allowed me to cut CSS frameworks completely out of my workflow. I mean, it’s that frameworks are bad or should not be used, but I personally leaned on them a lot for their grid systems. That’s no longer the case and the result is one less dependency in my stack and the liberty to write more vanilla CSS.

Prototyping Tools

Robin already mentioned Figma and that is totally in line with what I’m referring to. There seemed to be an explosion of innovation in prototyping tools. Sketch, Figma, InVision and, yes, Adobe all upped their games this year and web designers were the beneficiaries. These tools have opened up have made it easier to collaborate with other designs, critique work, get client feedback, and ultimately get into the browser faster. I have never spent less time in graphic design software and it’s been awesome.

Here’s a taste of what I’m referring to:

Contrast in Accessibility

Often when we talk about accessibility, the focus is on things like semantics, document structure, screen readers ARIA roles. It can get super complicated. That’s why I really enjoyed Lara’s recent post advocating for accessible UI. Aside from being extremely well-written, she presents commonsense approaches to improving accessibility in ways that go beyond code.

One of her suggestions to check color contrasts in the design to ensure good legibility. This one really resonated with me because I recently worked on a project with a visual brand that includes a lot of greens and yellows. Running our designs through the tools Lara recommends revealed that our work failed many accessibility checks. It also taught me that accessibility really does not favor greens and yellows.

Web Typography: Designing Tables to be Read, Not Looked At

If you didn’t catch Richard Rutter’s post on A List Apart, I’ll please go read that right now. Don’t worry, I’ll wait right here for you.

You back? Great!

This one was a splash of cold water in my face. Richard not only convicted me to honestly assess whether I over-design tables but also turned all my preconceptions about what a table is and what a good one looks like. Good design is problem solving and this post is one that reminds me design for solutions before aesthetics.

place-items

Chris snuck this property into a demo and I had no idea it existed. I had to forgive myself a little when I saw that browser support on it is low, but it is a really nice shortcut that combines the align-items and justify-items properties. You may have guessed why I love this: it comes in super handy with Grid and Flexbox. While support is limited it Chrome 59+ and Firefox 45+, I am stoked to see more browsers hop on board.


What are your picks for 2017?


2017 Staff Favorites is a post from CSS-Tricks

Fragmented HTML5 Video

Post pobrano z: Fragmented HTML5 Video

I have seen various implementations of the Voronoi Diagram. Perhaps you’ve seen one without knowing what it was. It almost looks like random stained glass:

Wikipedia:

In mathematics, a Voronoi diagram is a partitioning of a plane into regions based on distance to points in a specific subset of the plane.

It’s even possible to create a Voronoi diagram by hand, as eLVirus88 has documented.

I wanted to give it a try.

The Idea

My idea is to chop up a video into fragmented parts (called cells) and put them into 3D space on a slightly different z-axis. Then, by moving the mouse, you would rotate the whole experience so you would see the cells in different depths.

The Code

Building on top of Raymond Hill’s and Larix Kortbeek’s JavaScript implementation, the first thing I needed to was split up the cells.

I choose to use the <canvas> element, and put each of the cells on different canvas on a differnet 3D plane through CSS.

The Voronoi library takes care of computing all the sites to cells and creating objects with the vertices and edges for us to work with.

Cells to Canvases

First we create the canvases to match the number of Voronoi cells. These will be rendered to the DOM. The canvases and their respective contexts will be saved to an array.

var canv = document.createElement('canvas');
    
canv.id = 'mirror-'+i;
canv.width = canvasWidth;
canv.height = canvasHeight;

// Append to DOM
document.body.appendChild(canv);
document.getElementById('container-mirrors').appendChild(canv);

// Push to array
canvasArray.push(canv);
contextArray.push(canv.getContext('2d'));

Masking

All of the canvases are now a copy of the video.

The desired effect is to show one cell per canvas. The Voronoi library provides us with a compute function. When providing the sites with the bounds we get a detailed object where we extract all of the cells edges. These will be used to create a cut out to each section using the globalCompositeOperation.

// Compute
diagram = voronoi.compute(sites, bounds);

// Find cell
for (i=0;i<sites.length;i++) {
  if (!found) {
    cell = diagram.cells[i];
if (sites[j].voronoiId === cell.site.voronoiId) {
      found = 1;
    }
  }
}

// Create mask to only show the current cell
ctx.globalCompositeOperation = 'destination-in';
ctx.globalAlpha = 1;

ctx.beginPath();

var halfedges = cell.halfedges,
nHalfedges = halfedges.length,
v = halfedges[0].getStartpoint();

ctx.moveTo(v.x,v.y);

for (var iHalfedge=0; iHalfedge<nHalfedges; iHalfedge++) {
  v = halfedges[iHalfedge].getEndpoint();
  ctx.lineTo(v.x,v.y);
}

ctx.fillStyle = sites[j].c;
ctx.fill();

Adding Video

Displaying video to the canvas only takes a couple of lines of code. This will be executed on requestAnimationFrame:

v = document.getElementById('video');
ctx.drawImage(v,0,0,960,540);

It’s also possible to use a video input source (like a webcam), but I didn’t like the result as much for this demo. If you would like to know how to use the webcam to draw to canvas using the getUserMedia() method you can read about it here.

To optimise video drawing performance skip a few frames in between the requestAnimationFrame. Videos for the web are usually encoded with a frame rate not higher than 30 fps.

See the Pen Fragmented HTML5 Video – Demo 1 by virgilspruit (@Virgilspruit) on CodePen.

Conclusion

Demos like this are my favorite things to do. Seeing what’s out there and adding your own layer of interactivity to it. I’m looking forward to seeing what other people will be doing with this nice visual algorithm.

See the Pen Fragmented HTML5 Video – Demo 2 by virgilspruit (@Virgilspruit) on CodePen.

See the Pen Fragmented HTML5 Video – Demo 3 by virgilspruit (@Virgilspruit) on CodePen.

View Demos GitHub Repo


Fragmented HTML5 Video is a post from CSS-Tricks

Further working mode changes at WHATWG

Post pobrano z: Further working mode changes at WHATWG

The Web Hypertext Application Technology Working Group (WHATWG) announced that it has adopted a formal governance structure:

The WHATWG has operated successfully since 2004 with no formal governance structure, guided by a strong culture of pragmatism and collaboration. Although this has worked well for driving the web forward, we realized that we could get broader participation by being clear about what rights and responsibilities members of the community have. Concretely, this involves creating an IPR Policy and governance structure.

WHATWG was founded by folks at Apple, Mozilla and Opera. The new structure will be comprised of individuals from Apple, Google, Microsoft and Mozilla. The Big Four, you might say.

I find this interesting because we often think of the Web as a wild west where standards are always evolving and adopted at a different pace. This change largely keeps public contributions to the Living Standards in tact, but establishes a clearer line of communication between working groups and provides a path to appeal and resolve disputes over standards.

Living Standards are informed by input from contributors, driven by workstream participants, articulated by editors, and coordinated by the Steering Group. If necessary, controversies are resolved by the Steering Group with members appointed from the organizations that develop browser engines.

And, with representatives from leading browsers at the table, we may see more agreement with adoption. I’m speculating here, but it seems reasonable.

If you’re like me and are fuzzy on the differences between WHATWG and W3C, Bruce Lawson has a pretty simple explanation. It still kinda blows my mind that they’re both standards we often refer to but come from two completely different groups.

Direct Link to ArticlePermalink


Further working mode changes at WHATWG is a post from CSS-Tricks

Refactoring Your Way to a Design System

Post pobrano z: Refactoring Your Way to a Design System

Mina Markham on refactoring a large and complex codebase into an agile design system, slowly over time:

If you’re not lucky enough to be able to start a new design system from scratch, you can start small and work on a single feature or component. With each new project comes a new opportunity to flesh out a new part of the system, and another potential case study to secure buy-in and showcase its value. Make sure to carefully and thoroughly document each new portion of the system as it’s built. After a few projects, you’ll find yourself with a decent start to a design system.

As a side note, Mina’s point here also reminds me of an old blog post called „Things You Should Never Do” by Joel Spolsky where he talks about how all this work and all this code you feel you needs to be refactored is actually solving a problem. Deleting everything and starting from scratch is almost never a good idea:

When you throw away code and start from scratch, you are throwing away all that knowledge. All those collected bug fixes. Years of programming work.

I’m not entirely sure that Joel’s piece about programming fits snuggly with Mina’s point but I think it’s an interesting one to make nonetheless: new code doesn’t necessarily mean that it’s better.

Direct Link to ArticlePermalink


Refactoring Your Way to a Design System is a post from CSS-Tricks

Don’t Use My Grid System (or any others)

Post pobrano z: Don’t Use My Grid System (or any others)

This presentation by Miriam at DjangoCon US last summer is not only well done, but an insightful look at the current and future direction of CSS layout tools.

Many of us are familiar with Susy, the roll-your-own Grid system Miriam developed. We published a deep-dive on Susy a few years back to illustrate how easy it makes defining custom grid lines without the same pre-defined measures included in other CSS frameworks, like Foundation or Bootstrap. It really was (and is) a nice tool.

To watch Miriam give a talk that discourages using frameworks—even her very own—is a massive endorsement of more recent CSS developments, like Flexbox and Grid. Her talk feels even more relevant today than it was a few months ago in light of Eric Meyer’s recent post on the declining complexity of CSS.

Yes, today’s CSS toolkit feels more robust and the pace of development seems to have increased in recent years. But with it come new standards that replace the hacks we’ve grown accustomed to and, as a result, our beloved language becomes less complicated and less reliant on dependencies to make it do what we want.

Direct Link to ArticlePermalink


Don’t Use My Grid System (or any others) is a post from CSS-Tricks

Comparing Novel vs. Tried and True Image Formats

Post pobrano z: Comparing Novel vs. Tried and True Image Formats

Popular image file formats such as JPG, PNG, and GIF have been around for a long time. They are relatively efficient and web developers have introduced many optimization solutions to further compress their size. However, the era of JPGs, PNGs, and GIFs may be coming to an end as newer, more efficient image file formats aim to take their place.

We’re going to explore these newer file formats in this post along with an analysis of how they stack up against one another and the previous formats. We will also cover optimization techniques to improve the delivery of your images.

Why do we need new image formats at all?

Aside from image quality, the most noticeable difference between older and newer image formats is file size. New formats use algorithms that are more efficient at compressing data, so the file sizes can be much smaller. In the context of web development, smaller files mean faster load times, which translates into lower bounce rates, more traffic, and more conversions. All good things that we often preach.

As with most technological innovations, the rollout of new image formats will be gradual as browsers consider and adopt their standards. In the meantime, we as web developers will have to accommodate users with varying levels of support. Thankfully, Can I Use is already on top of that and reporting on browser support for specific image formats.

The New Stuff

As we wander into a new frontier of image file formats, we’ll have lots of format choices. Here are a few candidates that are already popping up and making cases to replace the existing standard bearers.

WebP

WebP was developed by Google as an alternative to JPG and can be up to 80 percent smaller than JPEGs containing the same image.

WebP browser support is improving all the time. Opera and Chrome currently support it. Firefox announced plans to implement it. For now, Internet Explorer and Safari are the holdouts. Large companies with tons of influence like Google and Facebook are currently experimenting with the format and it already makes up about 95 percent of the images on eBay’s homepage. YouTube also uses WebP for large thumbnails.

If you’re using a CMS like WordPress or Joomla, there are extensions to help you easily implement support for WebP, such as Optimus and Cache Enabler for WordPress and Joomla’s own supported extension. These will not break your website for browsers that don’t support the format so long as you provide PNG or JPG fallbacks. As a result, browsers that support the newer formats will see a performance boost while others get the standard experience. Considering that browser support for WebP is growing, it’s a great opportunity to save on latency.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Chrome Opera Firefox IE Edge Safari
23 12 No No No No

Mobile / Tablet

iOS Safari Opera Mobile Opera Mini Android Android Chrome Android Firefox
No 11.1 all 4.2-4.3 62 No

HEIF

High efficiency image files (or HEIF) actually bear the extension HEIC (.heic), which stands for high efficiency image container, but the two acronyms are being used interchangeably. Earlier this year, Apple announced that its newest line of products will support HEIF format by default.

On top of smaller file sizes, HEIF offers more versatility than other formats since it can support both still images and image sequences. Therefore, it’s possible to store burst photos, focal stacks, exposure stacks, images captured from video and other image collections in a single file. HEIF also supports transparency, 3D, and 4K.

In addition to images, HEIF files can hold image properties, thumbnails, metadata and auxiliary data such as depth maps and audio. Image derivations can be stored as well thanks to non-destructive editing operations. That means cropping, rotations, and other alterations can be undone at any time. Imagine all of your image variations contained in a single file!

Apple is doing everything it can to make the transition as seamless as possible. For example, when users share HEIF files with apps that do not support the format, Apple will automatically convert the image to a more compatible format such as JPG.

There is no browser support for HEIF at the time of this writing.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Chrome Opera Firefox IE Edge Safari
No No No No No No

Mobile / Tablet

iOS Safari Opera Mobile Opera Mini Android Android Chrome Android Firefox
No No No No No No

That being said, the file format offers impressive file savings for both video and images. This is becoming increasingly important as our devices become stronger and are able to take higher quality images and videos, thus resulting in a greater need for efficient media files.

FLIF

Free Lossless Image Format (or FLIF) uses a compression algorithm that results in files that are 14-74 percent smaller than older formats without sacrificing quality (i.e. lossless). Therefore, FLIF is a great fit for any type image or animation.

The FLIF homepage claims that FLIF files are 43% percent smaller on average than typical PNG files. The graph below illustrates how FILF compares to other formats in this regard.

FLIF often winds up being the most efficient format in tests.

FLIF takes advantage of something called meta-adaptive near-zero integer arithmetic coding, or (appropriately) MANIAC. FLIF also supports progressive interlacing so that images appear whole as soon as they begin downloading, which is another feature that has shown to reduce web page bounce rates.

The potential of FLIF is very exciting, but there is no browser support at the moment nor does it look like any browsers are currently considering adding it. While creators of the format are working hard on achieving native support for popular web browsers and image editing tools, developers can access the FLIF source code and snag a polyfill solution to test it out.

The Existing Stuff

As mentioned earlier, we’re likely still years away from the new formats completely taking over. In some cases, it might be better to stick with the tried and true. Let’s review what formats we’re talking about and discuss how they’ve stuck around for so long.

JPG

As the ruling standard for most digital cameras and photo sharing devices, JPG is the most frequently used image format on the internet. W3Techs reports that nearly three-quarters of all websites use JPG files. Similarly, most popular photo editing software save images as JPG files by default.

JPG is named after Joint Photographic Experts Group, the organization that developed the technology; hence why JPG is alternatively called JPEG. You may see these acronyms used interchangeably.

The format dates all the way back to 1992, and was created to facilitate lossy compression of bitmap images. Lossy compression is an irreversible process that relies on inexact approximations. The idea was to allow developers to adjust compression ratios to achieve their desired balance between file size and image quality.

The JPG format is terrific for captured photos; however, as the name implies, lossy compression comes with a reduction in image quality. Quality degrades further each time an image is edited and re-saved, which is why developers are taught to refrain from resizing images multiple times.

GIF

GIF is short for graphics interchange format. It depends on a compression algorithm called LZW, which doesn’t degrade image quality. The GIF format lacks the color support of JPG and PNG, but it has stuck around nonetheless thanks to its ability to render animations by bundling multiple images into a single file. Images stored inside a GIF file can render in succession to create a short movie-like effect. GIFs can be configured to display image sequences a set number of times or loop infinitely.

Image courtesy of Giphy.com

PNG

The good old portable network graphic (PNG) was originally conceptualized as the successor to the GIF format and debuted in 1996. It was designed specifically for representing images on the web. In terms of popularity, PNG is a close runner-up to JPG. W3Techs claims that 72 percent of websites use this format. Unlike JPG, PNG images are capable of lossless compression (meaning no image quality is lost).

Another advantage over JPG is that PNG supports transparency and opacity. Since large photos tend to look superior in the JPG format, the PNG format is typically used for non-complex graphics and illustrations.

Comparing the transparency support of JPG (left) and PNG (right).

Ways to Improve Image Optimization and Delivery

There are a few vital things to consider when optimizing images for the web because any file format—including the new ones—can end up adding yet another layer of complexity. Images typically account for the bulk of the bytes on a web page, so image optimization is considered low-hanging fruit for improving a website’s performance. The Google Dev Guide has a comprehensive article on the topic, but here is a condensed list of tips for speeding up your image delivery.

Implement Support for New Image Formats

Since newer formats like WebP aren’t yet universally supported, you must configure your applications so that they serve up the appropriate resources to your users.

You must be able to detect which formats the client supports and deliver the best option. In the case of WebP, there are a few ways to do this.

Invest in a CDN

A content delivery network (CDN) accelerates the delivery of images by caching them on their network of edge servers. Therefore, when visitors come to your website, they get routed to the nearest edge server instead of the origin server. This can produce massive time savings especially if your users are far from your origin server.

We have a whole post on the topic to help understand how CDNs work and how to leverage them for your projects.

Use CSS Instead of Images

Because older browsers didn’t support image shadows and rounded corners, veteran web developers are used to displaying certain elements like buttons as images. Remember the days when displaying a custom font required making images for headlines? These practices are still out in the wild, but are terribly inefficient approaches. Instead, use CSS whenever you can.

Check Your Image Cache Settings

For image files that don’t change very often, you can utilize HTTP caching directives to improve load times for your regular visitors. That way, when someone visits your website for the first time, their browser will cache the image so that it doesn’t have to be downloaded again on subsequent visits. This practice can also save you money by reducing bandwidth costs.

Of course, improper caching can cause problems. Adding a fingerprint, such as a timestamp, to your images can help prevent caching conflicts. Fortunately, most web development platforms do this automatically.

Resize Images for Different Devices

Figuring out how to best accommodate mobile devices with inferior screen resolutions is an ongoing process. Some developers don’t even bother and simply offer the same image files for all users, but this approach wastes your bandwidth and your mobile visitors’ time. Consider using srcset so that the browser determines which image size it should deliver based on the client’s size dimensions.

Image Compression Tests

It’s always interesting to see the size differences each image format provides. In the case of this article, we’re comparing lossless and lossy image formats together. Of course, that’s not common practice as many times lossy will be smaller in size than lossless as the quality of the image suffers in order to produce a smaller image size.

In any case, choosing between lossless and lossy image formats should be based on how image intensive your site is and how fast it already runs. For example, an e-commerce shop may be comfortable with a slightly degraded image in exchange for faster load times while a photographer website is likely the opposite in order to showcase talent.

To compare the sizes of each of the six image formats mentioned in this article, we began with three JPG images and converted them into each of the other formats. Here are the performance results.

As previously mentioned, the results below vary significantly due to lossless/lossy image formats. For instance, PNG and FLIF images are both lossless, therefore resulting in larger image files.

Image 1 Size Image 2 Size Image 3 Size
WebP 1.8 MB 293 KB 1.6 MB
HEIF 1.2 MB 342 KB 1.1 MB
FLIF 7.4 MB 2.5 MB 6.6 MB
JPG 3.9 MB 1.3 MB 3.5 MB
GIF 6.3 MB 3.9 MB 6.7 MB
PNG 13.2 MB 5 MB 12.5 MB

According to the results above, HEIF images were smaller overall than any other format. However, due to their lack of support, it currently isn’t possible to integrate the HEIF format into web applications. WebP came in at a fairly close second and does offer ways to work around the less-than-ideal amount of browser support. For users who are using Chrome or Opera, WebP images will certainly help accelerate delivery.

As for the lossless image formats, PNG is significantly larger than it’s lossy JPG counterpart. However, when optimized with FLIF, savings of about 50 percent were realized. This makes FLIF a great alternative for those who require high-quality images at a smaller file size. That said FLIF currently isn’t supported by another web browsers yet, similar to HEIF.


Conclusion

The old image formats will likely still be around for many years to come, but more developers will embrace the newer formats once they realize the size-saving benefits.

Cameras, mobile devices and many gadgets, in general, are becoming more and more sophisticated meaning that the images and videos taken are of higher quality and taking up more space. New formats must be adopted to mitigate this and it looks like we have some extremely promising options to look forward to, even if it will take some time to see them officially adopted.


Comparing Novel vs. Tried and True Image Formats is a post from CSS-Tricks

New in Chrome 63

Post pobrano z: New in Chrome 63

Yeah, we see browser updates all the time these days and you may have already caught this one. Aside from slick new JavaScript features, there is one new CSS update in Chrome 63 that is easy to overlook but worth calling out:

Chrome 63 now supports the CSS overscroll-behavior property, making it easy to override the browser’s default overflow scroll behavior.

The property is interesting because it natively supports the pull to refresh UI that we often see in native and web apps, defines scrolling regions that are handy for popovers and slide-out menus, and provides a method to control the rubber-banding effect on some touch devices so that a page does a hard stop at the top and bottom of the viewport.

For now, overscroll-behavior is not a W3C standard (here’s the WICG proposed draft). It’s currently only supported by Chrome (63, of course) which also means it’s in Opera (version 50). Chrome Platform Status reports that it is currently in development for Firefox and has public support from Edge.

Direct Link to ArticlePermalink


New in Chrome 63 is a post from CSS-Tricks

Using SVG to Create a Duotone Effect on Images

Post pobrano z: Using SVG to Create a Duotone Effect on Images

Anything is possible with SVG, right?!

After a year of collaborating with some great designers and experimenting to achieve some pretty cool visual effects, it is beginning to feel like it is. A quick search of „SVG” on CodePen will attest to this. From lettering, shapes, sprites, animations, and image manipulation, everything is better with the aid of SVG. So when a new visual trend hit the web last year, it was no surprise that SVG came to the rescue to allow us to implement it.

The spark of a trend

Creatives everywhere welcomed the 2016 new year with the spark of a colorizing technique popularized by Spotify’s 2015 Year in Music website (here is last year’s) which introduced bold, duotone images to their brand identity.

The Spotify 2015 Year in Music site demonstrates the duotone image technique.

This technique is a halftone reproduction of an image by superimposing one color (traditionally black) with another. In other words, the darker tone will be mapped to the shadows of the image, and the lighter tone, mapped to the highlights.

We can achieve the duotone technique in Photoshop by applying a gradient map (Layer > New Adjustment Layer > Gradient Map) of two colors over an image.

Choose the desired color combination for the gradient map
A comparison of the original image (left) and when the gradient map is applied (right)

Right click (or alt + click) the adjustment layer and create a clipping mask to apply the gradient map to just the image layer directly below it instead of the applying to all layers.

It used to take finessing the <canvas> element to calculate the color mapping and paint the result to the DOM or utilize CSS blend-modes to come close to the desired color effect. Well, thanks to the potentially life-saving powers of SVG, we can create these Photoshop-like “adjustment layers” with SVG filters.

Let’s get SaVinG!

Breaking down the SVG

We are already familiar with the vectorful greatness of SVG. In addition to producing sharp, flexible, and small graphics, SVGs also support over 20 filter effects that allow us to blur, morph, and do so much more to our SVG files. For this duotone effect, we will use two filters to construct our gradient map.

feColorMatrix (optional)

The feColorMatrix effect allows us to manipulate the colors of an image based on a matrix of rbga channels. Una Kravets details color manipulation with feColorMatrix in this deep dive and it’s a highly recommended read.

Depending on your image, it may be worth balancing the colors in the image by setting it to grayscale with the color matrix. You can adjust the rbga channels as you’d like for the desired grayscale effect.

<feColorMatrix type="matrix" result="grayscale"
  values="1 0 0 0 0
    1 0 0 0 0
    1 0 0 0 0
    0 0 0 1 0" >
</feColorMatrix>

feComponentTransfer

Next is to map the two colors over the highlights and shadows of our grayscale image with the feComponentTransfer filter effect. There are specific element attributes to keep in mind for this filter.

Attribute What it Does Value to Use
color-interpolation-filters (required) Specifies the color space for gradient interpolations, color animations, and alpha compositing. sRGB
result (optional) Assigns a name to this filter effect and can be used/referenced by another filter primitive with the in attribute. duotone

While the result attribute is optional, I like to include it to give additional context to each filter (and as a handy note for future reference).

The feComponent filter handles the color mapping based on transfer functions of each rbga component specified as child elements of the parent feComponentTransfer: feFuncR feFuncG feFuncB feFuncA. We use these rbga functions to calculate the values of the two colors in the gradient map.

Here’s an example:

The Peachy Pink gradient map in the screenshots above uses a magenta color (#bd0b91) , with values of R(189) G(11) B(145).

Divide each RGB value by 255 to get the values of the first color in the matrix. The RGB values of the second column result in #fcbb0d (gold). Similar to in our Photoshop gradient map, the first color (left to right) gets mapped to the shadows, and the second to the highlights.

<feComponentTransfer color-interpolation-filters="sRGB" result="duotone">
  <feFuncR type="table" tableValues="(189/255) 0.9882352941"></feFuncR>
  <feFuncG type="table" tableValues="(11/255) 0.7333333333"></feFuncG>
  <feFuncB type="table" tableValues="(145/255) 0.05098039216"></feFuncB>
  <feFuncA type="table" tableValues="0 1"></feFuncA>
</feComponentTransfer>

Step 3: Apply the Effect with a CSS Filter

With the SVG filter complete, we can now apply it to an image by using the CSS filter property and setting the url() filter function to the ID of the SVG filter.

It’s worth noting that the SVG containing the filter can just be a hidden element sitting right in your HTML. That way it loads and is availble for use, but does not render on the screen.

background-image: url('path/to/img');
filter: url(/path/to/svg/duotone-filters.svg#duotone_peachypink);
filter: url(#duotone_peachypink);

Browser Support

You’re probably interested in how well supported this technique is, right? Well, SVG filters have good browser support.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Chrome Opera Firefox IE Edge Safari
8 9 3 10 12 6

Mobile / Tablet

iOS Safari Opera Mobile Opera Mini Android Android Chrome Android Firefox
6.0-6.1 10 all 4.4 62 57

That said, CSS filters are not as widely supported. That means some graceful degradation considerations will be needed.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Chrome Opera Firefox IE Edge Safari
18* 15* 35 No 17 6*

Mobile / Tablet

iOS Safari Opera Mobile Opera Mini Android Android Chrome Android Firefox
6.0-6.1* 37* No 4.4* 62 57

For example, Internet Explorer (IE) does not support the CSS Filter url() function, nor does it support CSS background-blend-modes, the next best route to achieving the duotone effect. As a result, a fallback for IE can be an absolutely positioned CSS gradient overlay on the image to mimic the filter.

In addition, I did have issues in Firefox when accessing the filter itself based on the path for the SVG filter when I initially implemented this approach on a project. Firefox seemed to work only if the filter was referenced with the full path to the SVG file instead of the filter ID alone. This does not seem to be the case anymore but is worth keeping in mind.

Bringing it All Together

Here’s a full example of the filter in use:

<svg xmlns="http://www.w3.org/2000/svg">
  <filter id="duotone_peachypink">
    <feColorMatrix type="matrix" result="grayscale"
      values="1 0 0 0 0
              1 0 0 0 0
              1 0 0 0 0
              0 0 0 1 0" >
    </feColorMatrix>
    <feComponentTransfer color-interpolation-filters="sRGB" result="duotone">
      <feFuncR type="table" tableValues="0.7411764706 0.9882352941"></feFuncR>
      <feFuncG type="table" tableValues="0.0431372549 0.7333333333"></feFuncG>
      <feFuncB type="table" tableValues="0.568627451 0.05098039216"></feFuncB>
      <feFuncA type="table" tableValues="0 1"></feFuncA>
    </feComponentTransfer> 
  </filter>        
</svg>

Here’s the impact that has when applied to an image:

A comparison of the original image (left) with the filtered effect (right) using SVG!

See the Pen Duotone Demo by Lentie Ward (@lentilz) on CodePen.

For more examples, you can play around with more duotone filters in this pen.

Resources

The following resources are great points of reference for the techniques used in this post.


Using SVG to Create a Duotone Effect on Images is a post from CSS-Tricks

How Would You Solve This Rendering Puzzle In React?

Post pobrano z: How Would You Solve This Rendering Puzzle In React?

Welcome, React aficionados and amateurs like myself! I have a puzzle for you today.

Let’s say that you wanted to render out a list of items in a 2 column structure. Each of these items is a separate component. For example, say we had a list of albums and we wanted to render them a full page 2 column list. Each „Album” is a React component.

Scroll rendering problem

Now assume the CSS framework that you are using requires you to render out a two column layout like this…

<div class="columns">
  <div class="column"> Column 1 </div>
  <div class="column"> Column 2 </div>
<div class="columns">

This means that in order to render out the albums correctly, you have to open a columns div tag, render two albums, then close the tag. You do this over and over until all the albums have been rendered out.

I solved it by breaking the set into chunks and rendering on every other album conditionally in a separate render function. That render function is only called for every other item.

class App extends Component { 
  state = {albums: [] }

  async componentDidMount() { 
    let data = Array.from(await GetAlbums());
    this.setState({ albums: data } ); 
  } 

  render() { 
    return (
      <section className="section">
        {this.state.albums.map((album, index) => {
          // use the modulus operator to determine even items return index % 2 ?
          this.renderAlbums(index) : '';
        })}
      </section> 
    )
  }

  renderAlbums(index) { 
    // two albums at a time - the current and previous item
    let albums = [this.state.albums[index - 1], this.state.albums[index]]; 
    
    return (
      <div className="columns" key={index}>
        {albums.map(album => {
          return (
            <Album album={album} />
          );
        })}
      </div>
    );
  }
}

View Full Project

Another way to do this would be to break the albums array up into a two-dimensional array and iterate over that. The first highlighted block below splits up the array. The second is the vastly simplified rendering logic.

class App extends Component { 
  state = {albums: []}
  
  async componentDidMount() { 
    let data = Array.from(await GetAlbums());
    
    // split the original array into a collection of two item sets
    data.forEach((item, index) => {
      if (index % 2) {
        albums.push([data[index - 1], data[index]]);
      }
    });

    this.setState({
      albums: albums
    });
  } 

  render() {
    return ( 
      <section className="section">
        {this.state.albums.map((album, index) => { 
          return ( 
            <div className="columns">
              <Album album={album[0]}></Album> 
              <Album album={album[1]}></Album> 
            </div> 
          ) 
        })}
      </section> 
    ) 
  } 
}

View Full Project

This cleans up the JSX quite a bit, but now I’m redundantly entering the Album component, which just feels wrong.

Sarah Drasner pointed out to me that I hadn’t even considered one of the more important scenarios here, and that is the unknown bottom scenario.

Unknown Bottom

Both of my solutions above assume that the results set received from the fetch is final. But what if it isn’t?

What if we are streaming data from a server (ala RxJs style) and we don’t know how many times we will receive a results set, and we don’t know how many items will be in a given set. That seriously complicates things and utterly destroys the proposed solutions. In fact, we could go ahead and say that neither of these solutions are ideal because they don’t scale to this use case.

I feel like the absolute simplest solution here would be to fix this in the CSS. Let the CSS worry about the layout the way God intended. I still think it’s important to look at how to do this with JSX because there are people building apps in the real world who have to deal with shenanigans like this every day. The requirements are not always what we want them to be.

How Would You Do It?

My question is just that — how would you do this? Is there a cleaner more efficient way? How can this be done so that it scales with an unknown bottom? Inquiring minds (mine specifically) would love to know.


How Would You Solve This Rendering Puzzle In React? is a post from CSS-Tricks

Evolution of img: Gif without the GIF

Post pobrano z: Evolution of img: Gif without the GIF

Colin Bendell writes about a new and particularly weird addition to Safari Technology Preview in this excellent post about the evolution of animated images on the web. He explains how we can now add an MP4 file directly to the source of an img tag. That would look something like this:

<img src="video.mp4"/>

The idea is that that code would render an image with a looping video inside. As Colin describes, this provides a host of performance benefits:

Animated GIFs are a hack. […] But they have become an awesome tool for cinemagraphs, memes, and creative expression. All of this awesomeness, however, comes at a cost. Animated GIFs are terrible for web performance. They are HUGE in size, impact cellular data bills, require more CPU and memory, cause repaints, and are battery killers. Typically GIFs are 12x larger files than H.264 videos, and take 2x the energy to load and display in a browser. And we’re spending all of those resources on something that doesn’t even look very good – the GIF 256 color limitation often makes GIF files look terrible…

By enabling video content in img tags, Safari Technology Preview is paving the way for awesome Gif-like experiences, without the terrible performance and quality costs associated with GIF files. This functionality will be fantastic for users, developers, designers, and the web. Besides the enormous performance wins that this change enables, it opens up many new use cases that media and ecommerce businesses have been yearning to implement for years. Here’s hoping the other browsers will soon follow.

This seems like a weird hack but, after mulling it over for a second, I get how simple and elegant a solution this is. It also sort of means that other browsers won’t have to support WebP in the future, too.

Direct Link to ArticlePermalink


Evolution of img: Gif without the GIF is a post from CSS-Tricks