Home > Designing, Others > CSS2JS

CSS2JS

To add inline styles on an element in JSX, you have to do it in this object syntax, like:

<div style={{
  fontSize: 16,
  marginBottom: "1rem"
}}>
  Content
</div>

That might look a little weird to us folks who are so used to the CSS syntax, where it is font-size (not fontSize), margin-bottom (not marginBottom), and semi-colons (not commas).

That’s not JSX (or React or whatever) being weird — that’s just how styles are in JavaScript. If you wanted to set the font-size from any other JavaScript, you’d have to do:

div.style.fontSize = "16px";

I say that, but other APIs do want you to use the CSS syntax, like:

window.getComputedStyle(document.body)
  .getPropertyValue("font-size");

There are also lots of CSS-in-JS libraries that either require or optionally support setting styles in this object format. I’ve even heard that with libraries that support both the CSS format (via template literals) and the object format (e.g. Emotion), that some people prefer the object syntax over the CSS syntax because it feels more at home in the surrounding JavaScript and is a bit less verbose when doing stuff like logic or injecting variables.

Anyway, the actual reason for the post is this little website I came across that converts the CSS format to the object format. CSS2JS:

Definitely handy if you had a big block of styles to convert.

Direct Link to ArticlePermalink

The post CSS2JS appeared first on CSS-Tricks.

Categories: Designing, Others Tags:
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.