Optimise Your CSS With Shorthand Properties!

We use shorthand properties to set the values of multiple CSS properties simultaneously, resulting in more optimised and efficient code.

In this article, we will look at the most commonly missed areas to implement shorthand properties, compare them to their longhand counterparts, and learn the order of values for said properties.

Note: More about the other types of shorthand properties can be found here!

Background Properties

The following background properties can be shortened from…

Longhand

…to just one declaration:

Shorthand

This shorthand declaration is the equivalent to its longhand counterpart above. The order of values is crucial for the declaration and is as followed: background-color, background-image, background-repeat and then background-position.

You can also tag on the “background-attachment” property to the end of the declaration as-well-as some additional properties in CSS3; however, these aren’t as commonly used as the above.

Margin and Padding Properties

Shorthand versions of margin and padding values work exactly the same; both using shorthand properties to specify four separate values.

The following margin properties can be shortened from…

Longhand

…to just one declaration:

Shorthand

The order of values work in clockwise order starting from the top: top, right, bottom, then left. Both margin and padding properties follow the same structure and can be set out as shown above.

For these properties in particular we can go a step further and refine our declaration even more:

Shorthand

The first value (10px) being top and bottom, and the second value (5px) being left and right.

Border and Outline

Shorthand versions of border and outline values also work in the same way; each specify three values and are declared in the same way.

The following border properties can be shortened from…

Longhand

…to just one declaration:

Shorthand

This is the most commonly used shorthand property and many developers use it without even knowing. The order of values is as followed: border-width, border-style and then border-color.

Summary

Shorthand properties are a great way to optimise your style sheets and reduce the amount of code you need to write. There's really no reason not to use them - yes they force you to write code in a specific order which some developers may find hard to remember at first; however, in the long run, knowing these will save you time and improve your coding knowledge.

I like to talk about design principles and share my knowledge with fellow devs. Connect with me on LinkedIn https://www.linkedin.com/in/joenapper6/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store