Adding styles to child component in NextJs while using Styled JSX
Next.js provides us with two styling options:
- Styled JSX
- Writing styles in external files
Styled JSX
is a CSS-in-JS library that allows you to write encapsulated and scoped CSS to style your components. The styles you introduce for one component won't affect other components, allowing you to add, change and delete styles without worrying about unintended side effects.
Using Styled JSX
To add styling within a component using Styled JSX
, you can add styles within component as follows:
function Content() {
return (
<>
<p>Let's explore different ways to style Next.js apps</p>
<style jsx>
{`
p {
color: black;
}
`}
</style>
</>
)
}
function Container() {
return (
<div className="container">
<h1>Container Title</h1>
<Content />
<style jsx>{`
.container {
margin: 50px;
}
`}</style>
</div>
)
}
But if you wanted add styles to the child component, it wont work. Lets see through a example:
function Content() {
return (
<>
<p>Let's explore different ways to style Next.js apps</p>
<style jsx>
{`
p {
color: black;
}
`}
</style>
</>
)
}
function Container() {
return (
<div className="container">
<h1>Container Title</h1>
<Content />
<style jsx>{`
.container {
margin: 50px;
}
.container p {
color: blue;
}
`}</style>
</div>
)
}
You could directly add styles in the child component, but at times you need to style the component based on where it is being used. You could add styles to child component using:
- One-off global selectors
- Writing styles in external files
- Adding global styles
One-off global selectors
The recommended option would be to use One-off global selectors. Here is an example of how to write styles for child component in Styled JSX:
function Content() {
return (
<>
<p>Let's explore different ways to style Next.js apps</p>
<style jsx>
{`
p {
color: black;
}
`}
</style>
</>
)
}
function Container() {
return (
<div className="container">
<h1>Container Title</h1>
<Content />
<style jsx>{`
.container {
margin: 50px;
}
.container :global(p) {
color: blue;
}
`}</style>
</div>
)
}
Global styles
Its possible to add these style overrides in an external stylesheet say global.css
. Alternative to adding styles in stylesheet is defining the styles as global using Styled JSX <style global jsx>
as follows:
<style global jsx>{`
.container {
margin: 50px;
}
.container (p) {
color: blue;
}
`}</style>