Pfrex
Pfrex

Reputation: 169

Why won't the JSX CSS be applied?

I'm working off of the documents from the "Learn" section on the Next.js website. The CSS below does not get applied to the component if using the jsx style tag; however, if I add the CSS as an object literal attribute it gets applied. How can I to get the jsx style tag CSS to be applied?

This won't be applied:

import Layout from "../components/Layout";

export default function Post() {
  return (
    <Layout>
      <div className="container"> This is a div. <div/>


// This wont be applied
      <style jsx>{`
        .container {
            margin: 20;
            padding: 20;
            border: "1px solid #DDD;
        }
      `}</style>
    </Layout>
  );
}

But this works:

import Layout from "../components/Layout";

const layoutStyle = {
  margin: 20,
  padding: 20,
  border: "1px solid #DDD"
};

export default function Post() {
  return (
    <Layout>
      <div className="container" style={layoutStyle}> This is a div. <div/>
    </Layout>
  );
}

Upvotes: 4

Views: 3425

Answers (3)

mohammad reza Bahrami
mohammad reza Bahrami

Reputation: 21

Try this:

  <style>{`
     .container {
        margin: 20;
        padding: 20;
        border: 1px solid #DDD;
     }
   `}</style>

Upvotes: 2

Tech Sourav
Tech Sourav

Reputation: 134

This is not a good approach if you are using the next js on your website. You should use the next css in your project that is so easy to use and maintain your CSS files as well. Here is a documentation link to use next css.

https://github.com/zeit/next-plugins/tree/master/packages/next-css

Upvotes: 0

Pfrex
Pfrex

Reputation: 169

When using the object attribute the unit is not supplied and the border field value is in quotes.

const layoutStyle = {
  margin: 20,
  padding: 20,
  border: "1px solid #DDD"
};

For it to work with JSX CSS it needs to be normal CSS syntax!

.container {
     margin: 20px;
     padding: 20px;
     border: 1px solid #DDD;
}

Upvotes: 1

Related Questions