«   Previous tip

Chrome DevTools: Copy CSS styles as JavaScript compatible properties

Last updated: 11th November 2021
Copy CSS styles as JavaScript compatible properties

Introduction

You can now copy CSS styles as JavaScript, so the styles in your clipboard are compatible with CSS-in-JavaScript libraries.

How to copy CSS as JavaScript

To try this out:

  1. Inspect an element via DevTools.
  2. Right click on the styles within the Styles Pane.
  3. Select Copy all declarations as JS (or copy a single declaration).

Your clipboard now has a string which looks like this (excluding the curly braces):

{
    letterSpacing: '2px',
    textTransform: 'uppercase',
    textDecoration: 'none',
    textAlign: 'center',
    margin: '1em',
    padding: '25px 40px'
}

Notice, DevTools converts the properties to items such as letterSpacing instead of a hyphenated CSS property like letter-spacing.

Bonus: How to assign styles with vanilla JavaScript

As a bonus tip, if you want to start out with a simple vanilla CSS-in-JavaScript approach (assuming you have a solid use-case of course!), you could use Object.assign().

The Object.assign() method can copy an object onto a target object, such as the .style property of a DOM element. Here's the code:

const anchor = document.querySelector('a');

Object.assign(anchor.style, {
    color: 'white',
    letterSpacing: '2px'
});

Availability

This feature is currently in Chrome Canary, tested in version 98, and should make its way to regular Chrome soon.

Further Resource

DevTools has lots of interesting 'copy as' features.

«   Previous tip

Sign up to receive a developer tip, in the form of a gif, in your inbox each week