Things You Can Do With CSS Today

About The Author

An independent designer and front-end developer who’s trying to make everyone’s experience on the web better with a focus on progressive enhancement and … More about Andy ↬

Email Newsletter

Weekly tips on front-end & UX.
Trusted by 200,000+ folks.

The present and future of CSS are very bright indeed and if you take a pragmatic, progressive approach to your CSS, then things will continue to get better and better on your projects, too. Some of the really handy powers CSS gives you might have slipped you by, so in this article, Andy Bell will take a look into masonry layout, :is selector, clamp(), ch and ex units, updated text decoration, and a few other useful CSS properties.

CSS is great and getting better all the time. Over recent years, especially, it has evolved really fast, too. Understandably, some of the really handy powers CSS gives you might have slipped you by because of this, so in this article, I’m going to show you some really handy stuff you can do with modern CSS today, and also share some stuff that we can look forward to in the future.

Let’s dig in.

Masonry Layout

Masonry layouts became very popular with Pinterest, Tumblr and Unsplash, and up until recently, we tended to rely on JavaScript to assist with our layout, which is almost never a good idea.

Sure, you can use CSS multicol pretty darn effectively to achieve a masonry layout, but that approach can be problematic with tabbed-focus as it lays content out in columns. This creates a disconnect between the visual layout and the tabbing index.

Fast forward to today (well, very shortly in the future) and a masonry layout is pretty trivial, thanks to an update to CSS Grid. Here’s a complete masonry layout, with gutters, in 6 lines of CSS:

.masonry {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: masonry;
  grid-gap: 1rem;
}

The magic is in grid-template-rows set as masonry, which turns it into the “masonry axis”, thus providing the “filled in” layout we’ve all come accustomed to.

Let’s expand on this and explore a quick demo of creating a responsive masonry layout. Using a slightly modified version of the above CSS, we can replace the grid-template-columns line to use this auto grid method instead:

.masonry {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr));
  grid-template-rows: masonry;
  grid-gap: 1rem;
}

The minmax() function allows us to define what the smallest size is for our items, which for us, is 16rem. Then we tell minmax() what the maximum size should be for each item. We declare that as 1fr, which takes 1 portion of the remaining available space.

This definition of grid-template-columns allows our layout to break and stack if it runs out of horizontal space which the masonry axis then automatically sorts our remaining elements for us.

Note: Right now, masonry is only working in Firefox Nightly, or behind a flag, but the grid layout will still work perfectly in non-supporting browsers, making it a decent progressive enhancement target.

See the Pen Native Masonry Layout With CSS Grid by Andy Bell.

Rachel Andrew wrote a great article about CSS Grid Masonry and you can also read the CSS Grid Layout Module Level 3 editor’s draft here for technical details.

Masonry support is currently very low, but as anything on the web, working out what your minimum viable experience is, then building up with progressive enhancement is a resilient way to build things. If you must use a masonry layout, though: I would recommend sticking with the tried-and-tested Masonry.js for now, but stick a ticket in your backlog to replace with native CSS in the future!

Resources

The :is Selector

I imagine a lot of us have had to write some gnarly CSS like this in the past:

.post h1,
.post h2,
.post h3 {
    line-height: 1.2;
}

.post img,
.post video {
    width: 100%;
}

Thankfully, CSS has got our back again with the :is pseudo-class.

That CSS can now be hugely simplified into this instead:

.post :is(h1, h2, h3) {
    line-height: 1.2;
}

.post :is(img, video) {
    width: 100%;
}

When things get more complex, it gets even more useful, because you can chain other selectors, such as :not and :first-child, just like in the following demo:

See the Pen :is selector demo by Andy Bell.

The :is() pseudo-class works by taking a passed selector list then translating it into an expanded selector list for us. This allows us to write more compact code and for the browser to do what it does already.

If you have a complex project where specificity is crucial, then the :where() pseudo-class could be useful. The main difference between :is() and :where() is that :where() has zero specificity, whereas the :is() pseudo-class uses the most specific selector in the passed selectors collection. This becomes useful if you think that rules set in your :is() block might need to be overridden out-of-context. This MDN article shows a great example of that.

This :is() pseudo-class has fantastic browser support — aside from IE11 and Opera Mini — so I would absolutely recommend that you start using it today. I would suggest caution with the :where() pseudo-class, though, because right now, only Firefox and Safari support it.

Resources

Logical CSS Functions For Sizing

Responsive design has evolved into intrinsic design over the years as designers rightly push the boundaries of design on the web. There have been lots of hacks in the past — especially with fluid typography — that have been rather fragile, to put it lightly.

We do have some really useful CSS functions that help with sizing: min(), max() and clamp(). The min() function gets the smallest value from two passed parameters and max() does the opposite: grabs the largest value.

The clamp() function is even handier as it allows you to pass a minimum, a maximum and an ideal value. Because of this “locking”, ideal value, clamp() is being used more and more in fluid typography, like Dave Rupert’s legendary FitText because you get a guaranteed baseline, which prevents unpredictable outcomes. It’s the basis of all of these functions because if you set a good baseline as the minimum for min() and a good baseline as the maximum in max(), you’re getting that needed flexibility, insured by a sensible level of control.

These logical functions are way more useful than that though. Here’s a demo where I’m using them not just for a bit of fluid typography sizing, but also to size an avatar image effectively.

See the Pen Min and Clamp demo by Andy Bell.

In the demo, I’m using min() to size the image and also, calculate the border-radius in the same way. It’s incredibly subtle, but really helps to achieve high design detail on the web, which is great!

Una Kravets has written a fantastically useful article on the use cases of these functions. I also use it to create a flexible wrapper.

Resources

Specific Responsive Units For Typography

There are so many units in CSS that all cater to specific use cases. Did you know that there are units specifically for typography? Of course em and rem are font-size related, but ch and ex are based on the size of the letters themselves.

The ch unit is equal to the width of the 0 character of your rendered font in its size. This scales with the font too, so it’s a really handy way to limit the width of your text, which helps with readability. Also, keep in mind that in proportional typefaces, 1ch is usually wider than the average character width, often by around 20-30%.

The ex unit is equal to the height of the lowercase x character — also known as the “x-height” in more traditional typography. This is really useful for working accurately and responsively with the vertical axis of your typography. One really handy use case for this is making an SVG icon the same height as your text.

In the following demo, I’ve solved two problems with these units. First, I’ve limited the text length with ch and then used the ex unit to position a <sup> and <sub> element, more effectively. This has long been a pain in web design!

See the Pen CH and EX units demo by Andy Bell.

Resources

Updated Text Decoration Control

Text decoration is no longer boring. You can do loads now, thanks to some updates in Text Decoration Level 4. My favourite trick with this is creating a highlight style with text-decoration-thickness, text-decoration-skip-ink and text-decoration-color.

See the Pen Text decoration demo by Andy Bell.

I also like using these new properties to better control underline thickness for heading elements, as they can get pretty heavy in certain fonts.

I strongly recommend you watch this video by Jen Simmons where, as always, she explains CSS properties in a friendly easy-to-understand manner.

Resources

Scroll Margin

This snippet of CSS will vastly improve your websites:

[id] {
  scroll-margin-top: 2ex;
}

When a browser skips to an element with an id — often a heading in a long article like this one — the targeted element would sit flush to the top of the viewport. Not only did this not look great, but it caused issues for fixed headers too.

This property — scroll-margin-top — is the antidote to all of that and is incredibly useful. Check out this demo where I combine it with smooth scrolling:

See the Pen Scroll margin demo by Andy Bell.

Resources

Aspect Ratio

If there was ever something we needed desperately in responsive design, it was native aspect ratio. This is especially needed for embedded media, such as YouTube videos. There’s long been the ol’ padding hack for these containers, but a hack should only be a temporary thing.

Thankfully, we will have aspect-ratio support in major browsers soon.

If you enable layout.css.aspect-ratio.enabled in Firefox, the following demos will be a perfect square and a perfectly responsive YouTube video, respectively:

Square (1:1)

Below is a square that’s always going to keep the same aspect ratio, 1:1 — achieve by defining aspect-ratio: 1 / 1.

See the Pen Perfect square with aspect ratio by Andy Bell.

Video (16:9)

For videos, a square would be a quite uncommon format. Instead, we can use 16:9 be defining aspect-ratio: 16 / 9 on the box.

See the Pen Perfect video embed with aspect ratio by Andy Bell.

Even though aspect-ratio isn’t quite here yet, you should definitely start thinking about it — especially with images, as the following is likely to appear in all browsers as default styles, and is already in Firefox (69 onwards):

img, input[type="image"], video, embed, iframe, marquee, object, table {
  aspect-ratio: attr(width) / attr(height);
}

This is going to be really helpful in reducing page load jank because elements like <img /> will generate a correctly sized box for themselves before they load. My advice is to start adding width and height attributes to elements in the above code sample to give your users a better loading experience. You can find more details about this particular issue on MDN.

Also, speaking about useful articles: take a look at a handy article about the aspect-ratio unit here on Smashing Magazine, written by Rachel Andrew — I highly recommend you to read it.

Resources

Content-Visibility And contain-intrinsic-size

The last one on our tour is content visibility and how it can give us a huge performance boost. Because CSS lets you pretty much do anything, a browser has to calculate everything to render one single element. If you have a huge, complex page, it can result in some reasonably sluggish render and paint times.

The new content-visibility and contain-intrinsic-size properties have arrived to help this and they are great.

With content-visibility: auto, you can tell the browser not to worry about rendering the elements in there while they are outside of the viewport, which can have a massive impact on initial loading speeds. The only problem is that the element with content-visibility: auto set on it loses its height, so we set contain-intrinsic-size to something like 0 400px to hint at what sort of size the element will be when it’s loaded.

These properties allow the browser to skip the initial rendering and instead, as the elements with content-visibility: auto set on them scroll near the viewport, the browser will start to render them. Proper progressive loading!

This video by Jake Archibald demos it really well:

Jake Archibald gives a whirlwind tour in a video presenting the new features and proposals to help users improve the performance of their pages
A talk by Jake Archibald explaining some of the useful CSS features that were released in Chrome recently. Notably, content-visibility.

You can also read this great article, too.

Resources

Wrapping Up And What’s Coming Up

That’s a pretty cool new CSS, right? There’s loads more arriving soon and loads in the long-term pipeline too. We can look forward to Media Queries Level 5 which let us target the current ambient light level and whether or not the user prefers reduced data.

We’ve also got CSS Nesting in draft, which will give us Sass-like nesting capabilities like this:

.my-element {
    background: red;

    & p {
        background: yellow;
    }
}

We’re getting even more control too, with font metrics override descriptors and Cascade Level 5, which introduces layers to the cascade. Prototyping is happening with container queries too!

Lastly, there are some cool new tricks on the horizon, like scroll-linked animations, which will open the door wide-open to a new generation of creative work on the web.

In conclusion, the present and future of CSS are very bright indeed and if you take a pragmatic, progressive approach to your CSS: things will continue to get better and better on your projects too.

Further Reading

Smashing Editorial (vf, yk, il, mrn)