4

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>
  );
}
Pfrex
  • 159
  • 2
  • 13

3 Answers3

1

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;
}

Pfrex
  • 159
  • 2
  • 13
1

Try this:

  <style>{`
     .container {
        margin: 20;
        padding: 20;
        border: 1px solid #DDD;
     }
   `}</style>
  • Could you explain more? Why remove the jsx and it works? – 陳見綸 Oct 20 '22 at 02:54
  • @陳見綸 I have no idea – mohammad reza Bahrami Oct 21 '22 at 08:12
  • This is not correct. Without the jsx attribute, your css won't be scoped to the element/component. It will be treated as a "normal", global css class. So if you add a .container styles in another component, it will affect both cases. @pfrex answer looks correct to me. Specially since you said that the style above is actually being applied. It just needs to be formatted like normal css – Emil Dec 09 '22 at 14:36
0

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

Tech Sourav
  • 124
  • 1
  • 7