admin管理员组

文章数量:1287964

I started using Styled Components for my Next.js app. Exploring best practices for global styles using Styled Components. First part of the question is how to create global styles with Styled Components.

The second and more important part is whether it is good practice to use a bination of CSS files and Styled Components, or is it an anti-practice?

I started using Styled Components for my Next.js app. Exploring best practices for global styles using Styled Components. First part of the question is how to create global styles with Styled Components.

The second and more important part is whether it is good practice to use a bination of CSS files and Styled Components, or is it an anti-practice?

Share Improve this question edited Feb 15, 2023 at 15:59 Mayank Kumar Chaudhari asked Dec 15, 2021 at 15:22 Mayank Kumar ChaudhariMayank Kumar Chaudhari 18.7k13 gold badges67 silver badges153 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

To create global styles we can use createGlobalStyle function. For next.js project, you can do that in _app.js or _app.tsx file, depending on whether you are using typescript.

import type { AppProps } from "next/app";
import { createGlobalStyle } from "styled-ponents";

import Header from "@/ponents/Header";

const GlobalStyles = createGlobalStyle`
html,
body {
    padding: 0;
    margin: 0;
}

a {
    color: inherit;
    text-decoration: none;
}

* {
    box-sizing: border-box;
}
`;

export default function MyApp({ Component, pageProps }: AppProps) {
  return (
    <>
      <GlobalStyles />
      <Header></Header>
      <Component {...pageProps} />
    </>
  );
}

Of course, if you have more global styles you can export the GlobalStyles from other file, say globalStyle.js.

But then there is nothing out there that stops you from using CSS or SCSS for your global styles. You can always import the .css or .scss or any other supported CSS preprocessor file types as you would normally do.

import '@/styles/global.scss'

And this would work perfectly fine with your Styled Components as well. Though there is a little advantage you get by using createGlobalStyle. You can use all SCSS features without having to add SCSS dependency in your project. And a little drawback is that the auto-plete features of the ide don't work as well with styled-ponents as they do with .css and .scss files.

本文标签: