Jump to content
Slate Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate Marble
Slate Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate Marble
Sign in to follow this  
Rss Bot

Hot new CSS rules to try now

Recommended Posts

As the web has rapidly evolved, it almost seems that apologetic CSS has been left behind. Each week something happens, but seldom where it matters – the interface. The internet follows an almost everlasting converge-then-diverge-then-converge model in applications, and now it’s the turn of CSS. 

As more frameworks, ideas and standards have emerged, complexity has skyrocketed with more and more helper technologies being invented from necessity. Things have become far more complicated for developers as people expect more, but now they are slowly being merged into CSS as formal standards. CSS has become unrecognisable from its early inception in the 1990s.

And what to the future? We can probably say now that CSS of the future will see another divergence as different digital and physical devices and channels appear, even to a brand-new technology. We can probably also guess that CSS will provide straightforward access to even richer interfaces and that the ‘S’ curve in development complexity and development features will narrow and steepen.

But what for now? These are our picks for the latest, greatest and most useful updates to CSS. Read on to learn how to use feature queries to check if a feature is supported before you start relying on it; build custom, print-style layouts with CSS Grid; DRY out your code with CSS variables; take control of backgrounds with two  background-repeat options (Round and Space); explore aspect-ratio based media queries; create unique visuals with blend-mode; and make images adjust to fill content boxes with Object-fit; and more. Use the quick links box opposite to jump to the section you want.

Feature queries (@supports)

When building components that use new and potentially unsupported features, it’s important to include a fallback. Until recently, this was achieved using feature detection via JavaScript with plugins such as Modernizr. Now, it is possible directly inside CSS using the new @supports syntax (also known as a feature query).

With the addition of @supports, we can check whether the code we would like to use is or is not supported:

When the page is loaded, a check will be performed to see if the browser in use supports the flex feature. If it does, the styling within the support braces will be applied by the browser. 

If it is not, it will be ignored – it is worth having a fallback option for when the feature being queried is not supported.

The most appropriate way to include the fallback code will depend on the project and what is being changed as there may be @supports code overriding default styling. In other cases, it may be preferable to include another @supports check to see if code is not supported. This is achieved with by negating the feature query:

Multiple checks can be combined to see if all the required features are supported at the same time, in order to apply either all or none of the style rules atomically. The syntax for this is very similar to combining media queries, such as applying styles on devices between specific sizes. This is achieved by using the ‘and’ operator and multiple feature queries:

The counterpart combination query for the and operator is the or operator, which checks if either of the feature queries matches and applies the style if at least one is supported:

Something which is useful given that we have already covered CSS variables is that with @supports you can also check to see if a custom property is supported or not, which can be done with the following approach:

With the above example a check will be carried out to see if the custom property condition is supported and when it is the body will have a font colour of orange applied. @supports is available to use in all browsers with the exception of IE 11 and below, although some polyfills are available if you do need to support as far back as Internet Explorer 9.

A final note: This is a great way to build in new styling rules, but it is also just as helpful at ensuring you build websites that degrade gracefully. If you use @supports then also use it to check if the browser does not support your CSS rules. This might double your workload, but it also ensures you create something that downscales browsers more elegantly.

CSS Grid

eGtKLUfG8Wwb9cHqgA35PZ.jpg

Build print-style layouts with less code than ever before 

The arrival of Flexbox has allowed us to spend less time polluting our code with clear fixes, hacks and workarounds, and focus more on writing concise CSS and HTML. While Flexbox is essential for any UI dev’s toolbox, it’s best suited for working in one single direction at a time. This is usually enough, as we are usually only restricted on one axis at a time (for example, the width of the page is restricted, but not the height). 

However, in the cases where we are restricted in both dimensions, say a dashboard style app, then CSS Grid is definitely one to shine. Starting off with the grid can be daunting at first, but it’s smooth sailing once you get to grips with the syntax. Say we have the following HTML structure:

We can define the grid, set the dimensions, and then define named areas for our grid cells:

Finally, on the .container we can make use of the grid-template-areas property to lay out what we want the grid to look like:

Additionally there are a whole host of additional properties to fine tune the presentation of the grid. To name a few:

grid-column-gap: <size>; Gutter between columns

grid-row-gap: <size>; Gutter between rows

grid-template-columns: <size>; Width of columns, space separated for multiple

grid-template-rows: <size>; Width of row, space separated for multiple

align-items: <center | end | start>; Vertically align the contents of each grid cell

align-items: <stretch>; Vertically fill the cell entirely

justify-items: <center | end | start | stretch>; As above, along the horizontal axis

place-items: <align-items> / <justify-items>; Shorthand notation, combining align-items and justify-items

So in practice, we could update our previous grid:

This is all just barely scratching the surface of the possibilities of CSS Grid – there’s so much more that can be done. Currently this is supported in all modern browsers, with IE11 being the exception, whereas it supports the older syntax.

But, wait, there’s more! With the use of CSS Grid we’re finally able to centrally align content without the stress:

Next page: CSS filters and CSS variables

CSS filters

CSS filters are probably one of the most powerful aesthetic tools you can use in your code to update the appearance of your build. With them, you can edit images using only CSS. There are several effects you can apply with CSS filters: blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, sepia, and SVG. 

TrWyKcCZGEVRXTJj38dPSZ.jpg

Clockwise from top left: blur, greyscale, hue-rotate, saturate (click the icon in the top right to enlarge the image)

Let's take a look at a few of them in more detail. In the image above, clockwise from top left, we have:

blur(5px)
Works by defining a blur size in px to your image; the higher the number the greater the blur (blur(10px) would create a strong blur effect).

grayscale(100%)
The value to change to complete grayscale would be 100% or 1, and to change to semi-grayscale you could use 50% or .5.

hue-rotate(90deg)
Probably the most unpredictable filter, this works by rotating the colour balance of the image, in degrees, turn or radians.

saturate(1)
Changes the colouring of the image making everything more vibrant; 1 or 100% results in complete saturation.

Importantly, you can also chain some of these effects together. So, for example, so you can apply a contrast and grayscale effect to an image. The good thing about the filter code is its simplicity. It is easy to remember and understand what is going on. To apply three chained filters to an image (blur, hue-rotate and drop-shadow), you would write:

There are some known issues with filters, including issues with ordering when chaining effects, which can sometimes have adverse effects. For example, if you were to apply grayscale after sepia it would result in an entirely greyed-out image. Browser support is also a little problematic. There is no support in Opera Mini, IE 11 and below, and Edge only has partial support.

CSS variables (custom properties)

Within CSS, to reuse code throughout a build, you used to have to type it out manually over and over, then preprocessors came along and the world was good – except you had to install and compile them, which wasn’t always as easy as it should be.

CSS custom properties enable you to pass through a string of content into your code, such as a colour or size. Unlike with preprocessors, you can update the variable to be something different when used within a media query, which means you no longer need to declare a specific variable to be used in each media query.

The variable is declared inside :root and is then applied to your tag via the var(--variable-name) code. As you can see by the example above, we have then overwritten those variables for screen sizes larger than 768px so we no longer need to create an individual variable for each breakpoint we support.

The overall simplicity and cascading element of CSS variables makes it easier and cleaner to use in your build than variables within preprocessors. You can create much cleaner default styling throughout your build while still using the same variable.

CSS variables can also be nested within one another, which can be helpful when working with large builds that are changing frequently. For example, you could do the following:

Overall, it is debatable whether you should use CSS variables or not. Ultimately it all depends on what you have to support for the build you’re doing. As far as browser support goes, variables are supported in all browsers except for Opera Mini, Samsung Internet 4 and old faithful Internet Explorer 11 as always.

One thing worth mentioning is that Microsoft Edge does support variables, but with a few known issues in release 15. You can not apply a CSS variable to an item that is a pseudo element (such as ::before and ::after) – this causes issues when applying background or border colours, and applying animations to pseudo elements. 

Animations that use CSS variables have been known to cause the browser to crash entirely (not ideal). Finally, nesting variables within variables causes an error that results in the browser not reading the variable at all; therefore no value is assigned to your component.

Next page: Background-repeat, aspect-ratio, blend-mode

Background-repeat (Round and Space)

Background-repeat has been a stable part of CSS for what seems like an eternity, but there are two lesser-known options available – Round and Space. Both of these options work by ensuring that 100 per cent of the background image declared is repeated and visible at all times. They work in slightly different ways and will make a subtle difference to how images appear. 

PHTHeFusnB4yab7HW8XVPZ.jpg

The round option resizes your image to fit

background-repeat: round; repeats your background image without ever cropping the image. Instead, it will resize the image evenly until there is enough space to fit in an extra tile.

wTrGCdoRaUP4ryWmXiCBRZ.jpg

The space option creates extra space between your tiles

Background-repeat: space; tiles the image in both directions. It's similar to Round, except instead of resizing the image until there is more space to display another tile, it will instead create white space between the tiles until another row or column can be shown.

Neither of these options is that new, but they will give you that little bit of extra control over the way tiling takes place over various viewport sizes. What is also very useful about these options is that they are supported by every browser.

aspect-ratio media queries

The introduction of media queries changed the way we build websites. We were given the opportunity to build our layouts depending on the way the user viewed the page. More often than not this would be based purely on the viewport width or height, but recently there has been a new option added.

Now you are able to apply CSS based on the page’s viewport via a media query that detects the aspect ratio of the window you’re browsing with. You are also able to detect whether the window matches a maximum or minimum aspect ratio.

EDnWdWkisvp8uvfqwnmqNZ.jpg

Click the icon in the top right to enlarge the image

The code to use for this is fairly simple. It matches the convention used with any other media query declaration – something like:

There are only a few scenarios in which aspect-ratio media queries would be useful. If you are building something specifically for mobile devices, you could use the min/max aspect-ratio to target whether the user is browsing in landscape or portrait mode (although this use could also be addressed with orientation media query). 

However, aspect-ratio is supported by all major browsers support it, with Internet Explorer support going as far back as version 9.

Blend-mode

Applying background images is typically a stable part of every project build. But sometimes it's good to be a little more creative with our background images, which is where blend-mode comes in.

Instead of just putting the background on top of the background colour, blend-mode combines the background image with the background colour in a defined style. The options you can use are normal, multiply, screen, overlay, darken, lighten, colour-dodge, saturation, colour and luminosity. 

r9ZwbjiUdbcx8WhcvTFgPZ.jpg

Clockwise from top left: overlay, difference, chained effects, luminosity (click the icon in the top right to enlarge the image)

Let's take a look at some of the options. In the image above, we have:

Overlay (top left)
Mixes both the background image and colour together to echo the darkness or lightness of the backdrop area.

Difference (top right)
Subtracts the darker colours from the background image/colour from the lightest shades, to give a very high contrast effect.

Luminosity (bottom left)
Preserves the top colour while fading hue and saturation of the background, to give a washed-out, old photo look.

The code to use for blending your background is fairly simple – all you need is one line of CSS to merge the background image with the background colour:

When it comes to applying blends to your background image you needn’t use just one mode. You can chain multiple blending modes together to create a more unique effect (shown in the bottom right of the image above) by using something similar to the code below:

Blend modes are supported in almost all browsers (including all versions of Microsoft Edge), with the exceptions being all versions of Internet Explorer and Opera Mini. 

Next page: Object-fit, shape-outside, currentColour and more

Object-fit

Wyjnt3cv4QaHJh9Begf9PZ.jpg

A more reliable way to present media

To make an image fill a content box, we have had to make use of the background-size: cover|contain styles. However, attempts to recreate this behaviour for images or videos have been somewhat clunky.

Thankfully the object-fit property has emerged, seemingly out of nowhere, to help. This can be used to achieve the same result, but on media assets such as images and videos. Object-fit can take five values:

fill
Stretches the asset to fit the parent container.

contain
Scales the asset to fit inside the parent container, maintaining aspect ratio (similar to background-size: contain).

cover:
Scales the asset to completely fill the parent container, cropping from the sides where necessary (similar to background-size: cover).

Scale-down
Similar to contain, however, this will only scale the asset down, and not make it larger than it is natively.

none
Render the asset as it would normally.

This property can also be combined with object-position to determine where the asset should be scaled from. Applying object-fit to your images is fairly simple:

It is important to remember height and width of the area you’d like to cover, otherwise the image will take on its default aspect ratio. This will most likely result in the image spanning the entire width of your available area.

In terms of browser support, object-fit is quite compliant, as it is supported in all browsers with two exceptions. There is no support at all in Internet Explorer, while Microsoft Edge supports object-fit on images only. 

Shape-outside

Something that has previously been lacking from CSS was the ability to wrap content cleanly around images that do not have squared edges. Now with the introduction of shape-outside, you can create more adaptive layouts that resemble something closer to a magazine layout than our old standard floated block images. 

To use shape-outside, first apply it to a floated element such as an image. Then in your CSS, declare which shape method you would like to use. The options available are:

  • circle – Create circular shapes
  • ellipse – Create elliptical shapes 
  • inset – Create rectangular shapes 
  • polygon – Create any shape with three or more vertices 
  • url – identifies which image should be used to wrap text around (works by placing text within the transparent areas of the image

Support for shape-outside isn’t particularly good yet, as Internet Explorer, Edge and Opera Mini all offer no support, but Firefox has now begun supporting it from release 62 onwards. The support of shape-outside in Microsoft Edge is currently under consideration, but there is no official word on when it could be implemented.

currentColour

currentColor is something that has creeped into our daily code usage. You declare your colour of choice via color: #000; and then when you want to apply the colour to something else like a border, for example, you would use border: 1px solid currentColor;. This will result in the border colour matching the declared text colour. 

Additionally, the colour then cascades down as your styling changes. Pretty cool, eh? If you were to declare a colour on a link and then apply currentColor to a border and SVG icon within that link, these would also change when you declare your hover and focus states like all responsible developers should be declaring.

Other CSS properties to explore

01. Will-change

This relatively new CSS feature has little impact on the appearance of your page – it is more of a processing tool than anything. The idea with will-change is to help the browser understand and prepare for elements of your code that will change when interacted with. 

For example, when interactions are performed with CSS, the browser will do the best it can to plan ahead for what changes may occur. And with the addition of will-change you can notify the browser in advance of what may change so it can prepare better. This will result in any interactions you need being more responsive.

02. Read-only

The read-only pseudo selects elements that are not editable by the user. Combined with the :read-write selector, they form a simpler way to style disabled, read-only and content-editable HTML. This is especially useful when building forms that have some read-only inputs showing existing, non-editable data.

03. ::playing and ::paused 

The ::playing or ::paused pseudo elements can be applied to highlight a component when it is currently being played or is paused, which will be useful if you’ve ever got any videos in your build. Unfortunately this code is in draft so it not fully supported yet.

03. Environment variables

Environment variables function in a similar way to CSS variables, but do not allow for overwriting. An environment variable defined once is guaranteed to have the same value throughout the document, whereas CSS variables (custom properties) can be overwritten on a component level and changes will cascade down to child declarations.

04. :focus-within

Probably one of the most eagerly anticipated newcomers, this selector is active when the user has focused a child element. This is especially helpful for exposing elements for keyboard accessibility.

05. Shape media-query

Most web devices are designed and implemented for rectangular devices. However, with the rising popularity of wearables, we are seeing more and more round devices on the market. The shape media-query can be used to target rectangular and round devices. This is specifically useful for ensuring everything fits onto the appropriate device’s screen.

06. Scroll anchoring

The introduction of scroll anchoring addresses one of the most frustrating problems that happens on the web: when you unintentionally click on a re-positioned element after late-loading content in your page finally displays. Scroll anchoring aims to solve this problem by forcing the browser to maintain your viewport position when content is loaded to the page.

07. Regions

The core concept behind regions is being able to say, 'Display this content over there instead'. By setting an area of the document as a named region, content from other parts of the page can be moved into a different part of the document flow. Unfortunately, the draft for CSS Regions has not been updated in some time and may be dropped.

This article was originally published in creative web design magazine Web Designer. Buy issue 277 or subscribe.

Read more:

View the full article

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

×