CSS-Only Resizable Elements

In Playing With (Fake) Container Queries Chris used the <resize-asaurus> web component to make the elements resizable. Curious to see how that worked I dug into its source.

As I was expecting a truckload of JavaScript to make it work, I was very surprised to see that it basically revolved around using just one single CSS property: resize

The resize CSS property sets whether an element is resizable, and if so, in which directions.

Accepted values for resize are none, horizontal, vertical, and both.

To play nice with CSS Logical Properties the values block and inline will also be supported.

πŸ˜… Up until then I thought resize was a thing reserved for <textarea> only.

~

Demo

To get resize working, one must apply it on a block level element + also set overflow to any value but visible. Below is a demo with resize set to both:

See the Pen
Resizable Element (Pure CSS)
by Bramus (@bramus)
on CodePen.

Don’t forget to set min-width/min-height/max-width/max-height in case you want to prevent the resizable box from becoming too small/big.

~

Resizing iframe elements

A very practical use-case for this is resiable iframe elements: As many embedded CodePen pens are responsive, you want your visitor to be able to resize them.

πŸ™ƒ As by coincidence, Ahmad asked for exactly this on Twitter just yesterday:

Could this be a task for CSS resize property you ask? Why yes, but there’s one big problem though: resize and <iframe> don’t play nice together.

Of course, as with many web things, there’s a little workaround we can use:

  1. Wrap the <iframe> in a <div>, and make the <div> resizable.
  2. Have <iframe> strech along with the <div>‘s dimensions, using Flexbox.

Like so:

See the Pen
Resizable iframe (Pure CSS)
by Bramus (@bramus)
on CodePen.

~

Browser Support

Resize is supported in all major browsers, except for MobileSafari (e.g. Safari on iOS). A shame though, as this once again pushes MobileSafari into the “(Mobile)Safari is the new IE6” corner …

Data on support for the css-resize feature across the major browsers from caniuse.com

πŸ’‘ Shown above is a dynamic CanIUse.com image, showing an always up-to-date support table. By the time you are reading this browser support might have become better.

Sidenote: @supports vs. resize: both; vs. MobileSafari

In the demo above I wanted to show a warning in browsers that don’t support resize: both;. For that I tried using @supports, which has proven to be successful before.

.warning {
	display: block;
}

/* Hide warning in case browser supports resize: both; */
@supports (resize: both) {
    .warning {
        display: none;
    }
}

MobileSafari however also hides the warning and thus falsely claims to support resize: both.

I’ve reported a bug on this: https://bugs.webkit.org/show_bug.cgi?id=211994

~

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would always put a smile on my face. Thanks!

β˜•οΈ Buy me a Coffee (€3)

ESNext: Proposals to look forward to (JS VidCon / JavaScript Remote Conf)

The past few days I’ve been attending some virtual conferences. At JS VidCon and JavaScript Remote Conf I also joined as a speaker, to bring forward my ever-evolving talk β€œESNext: Proposals to look forward to”

With the yearly ECMAScript releases (ES2015..ES2020) of a lot of things have changed in JavaScript-land, and there’s even more to come. This talk takes a look at a few of the newest (ES2020) and some of the upcoming ECMAScript features, which (hopefully) will become part of the ECMAScript Language Specification in the near future.

The slides are up on slidr.io, and also embedded below:

Talk Outline:

  • JavaScript Yellow: How to get JavaScript Yellow on your website (a plea to using the right tool for the right job)
  • TC39: Info on TC39, what they do, and how they work.
  • ESNext Proposal: Field Declarations
  • ESNext Proposal: Pipeline Operator
  • ES2020 Feature: Optional Chaining
  • ES2020 Feature: Null Coalescing
  • ESNext Proposal: Logical Assignment
  • ES2020 Feature: Dynamic Imports
  • ESNext Proposal: Export Default From
  • ESNext Proposal: Decimal
  • ESNext Proposal: Cancellation API (+ Mention of AbortController)
  • ESNext Proposal: Declarations In Conditionals
  • ESNext Proposal: Slice Notation
  • ES2019 Feature: Object.fromEntries()
  • ESNext Proposal: Pattern Matching
  • Fin.

Thanks to the organisers for having me, and thanks to the attendees for coming to see me. I hope you all had fun attending this talk. I know I had making it (and whilst bringing it forward). A shame we couldn’t meet in person though, perhaps at a next edition πŸ˜‰

πŸ’β€β™‚οΈ If you are a conference or meetup organiser, don’t hesitate to contact me to come speak at your event.

Unreal Engine 5

Unreal Engine 5 empowers artists to achieve unprecedented levels of detail and interactivity, and brings these capabilities within practical reach of teams of all sizes through highly productive tools and content libraries.

Whether you’re a gamer or not, I think we can all agree that this is very impressive stuff! 🀯

useWorker() – Use Web Workers with React Hooks

useWorker() is a js library (with typescript support) that allows you to use the Web Worker Web API, through React Hooks. This library allows you to run the expensive function without blocking the user interface, using a simple syntax that makes use of Promise

import React from "react";
import { useWorker, WORKER_STATUS } from "@koale/useworker";

const numbers = [...Array(5000000)].map(e => ~~(Math.random() * 1000000));
const sortNumbers = nums => nums.sort();

const Example = () => {
  const [sortWorker, { status, kill }] = useWorker(sortNumbers);
  const runSort = async () => {
    const result = await sortWorker(numbers); // non-blocking UI
    console.log("End.");
  };
  return (<button type="button" onClick={runSort}> Run Sort</button>);
};

Installation per NPM/Yarn:

npm install --save @koale/useworker

useWorker()
useWorker() Source (GitHub) →

πŸ€” Unfamiliar with Web Workers? Check out Handling JavaScript events with Web Workers then!

Pose Animator – Animate SVG Illustrations using your Camera

This is crazy:

Pose Animator takes a 2D vector illustration and animates its containing curves in real-time based on the recognition result from PoseNet and FaceMesh. It borrows the idea of skeleton-based animation from computer graphics and applies it to vector characters.

Built on top of PoseNet to track the body’s pose, and the aforementioned FaceMesh to track the face.

Pose Animator →
Pose Animator Demos →

PHPUnit: A Security Risk?

The author of PHPUnit was a bit surprised when he received a mail stating that PHPUnit was a security risk and hackers could remotely execute PHP code through a file named eval-stdin.php that ships used to ship with PHPUnit.

// eval-stdin.php
eval ('?>'. \file_get_contents('php://input'));

Even though the eval-stdin.php file itself indeed was vulnerable, it never should have been actively exploitable because:

  • PHPUnit is a dev dependency, and should never be installed in production.
  • One should never make their vendor folder publicly accessible. If it is placed in the wwwroot, use .htaccess or the like to prevent direct access to it.

Eventually a fix landed in PHPUnit, accompanied by this nice commit message:

This check should not be required ... yet here it is.

If you upload PHPUnit to a production webserver then your deployment process is broken.

If your vendor/ directory is publicly accessible on your webserver then your deployment process is broken.

*sigh*

PHPUnit: A Security Risk? →

Cleverly Cropping Images on Twitter using AI

To crop uploaded images, Twitter doesn’t simply cut them off starting from the center. After first having used Face Detection, they – in 2018 already – switched to AI to cleverly crop uploaded images.

Previously, we used face detection to focus the view on the most prominent face we could find. While this is not an unreasonable heuristic, the approach has obvious limitations since not all images contain faces.

A better way to crop is to focus on β€œsalient” image regions. Academics have studied and measured saliency by using eye trackers, which record the pixels people fixated with their eyes. In general, people tend to pay more attention to faces, text, animals, but also other objects and regions of high contrast. This data can be used to train neural networks and other algorithms to predict what people might want to look at. The basic idea is to use these predictions to center a crop around the most interesting region.

πŸ’‘ Note that depending on how many images you upload, Twitter will use a different aspect ratio.

What I find weird is that this clever cropping only works on their website, and not in embeds nor other clients. Take this tweet for example, embedded below:

When viewed on the Twitter website it does use the clever cropping:

Now, it wouldn’t surprise me that Twitter hides this extra information from 3rd party clients, given that they basically imposed a no-fly zone back in the day.

Speedy Neural Networks for Smart Auto-Cropping of Images →

Spacing grid/flexbox items in CSS with the gap property

Flexbox layout with CSS gap applied

The gap property for Flexbox about to land in Chromium 85. It allows you to define the size of the gutters between Grid/Flexbox children.

CSS Grid brought a delightful spacing feature called grid-gap, which quickly became a popular way to put space into layouts. It was easy to fall in love with because it took upon itself so much responsibility with such elegance. Starting in Chromium 85 grid-gap is now just gap, and you can use it with Flexbox. πŸ’ͺ

So no more grid-gap, but simply gap:

.layout {
-  grid-gap: 1em;
+  gap: 1em;
}

~

Why use gap (and not margin)?

Margins in flexbox don’t collapse, so when working with margin you’ll have to adjust the value you’re using. Because of this you’ll also get edges on the inside of your container, as the margin applied on the children is pushing the children inwards. Compare the screenshot below (using margin) with the one at the top of this post (using gap).

Flexbox layout with CSS margin applied
A margin of 1em is applied. Note the broader width between items and the extra blue edge on the container, all due to margins not collapsing.

~

Demo

See the Pen
Flexbox Gap
by Bramus (@bramus)
on CodePen.

Sidenote: @supports vs. Flexbox Gap

In the demo above I wanted to show a warning in browsers that don’t support flexbox gap. For that I tried using @supports, which has proven to be successful before.

.warning {
    display: block;
}

/* Hide warning in case browser supports flexbox gap */
@supports (display: flex) and (gap: 1em) { /* DOES NOT WORK AS INTENDED! */
    .warning {
        display: none;
    }
}

But that’s not really working as intended. In Chromium < 85 – which does not support flexbox gap – the warning is hidden, this because both conditions are evaluated separately:

  • Does Chromium < 85 support display: flex? Yes
  • Does Chromium < 85 support gap: 1em? Yes (from CSS Grid)

This makes me wonder whether re-using property names remains a good idea or not

Perhaps an extension to css-conditional should be made so that it supports a combination of properties β€” e.g. @supports (display: flex; gap: 1em)?

I’ve filed an issue for the latter.

~

Shorthand

gap is a shorthand for row-gap and column-gap:

.layout {
   display: flex;
   gap: 1em 2em;
}

The first value targets row-gap, the second value column-gap.

~

Browser Support

Firefox has supported it ever since version 63. Chromium is the first engine to follow its lead.

Data on support for the flexbox-gap feature across the major browsers from caniuse.com

πŸ’‘ Shown above is a dynamic CanIUse.com image, showing an always up-to-date support table. By the time you are reading this browser support might have become better.