Styled JSX is a CSS-in-JS library that allows you to write encapsulated and scoped CSS to style your components. This blog post will help you get started with using Styled JSX in Next.js.
Published By From Next.js Blog · 1 min read
WebStyling Next.js with Styled JSX
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.
Next.js includes Styled JSX by default, so getting started is as simple as adding a <style jsx> tag into an existing React element and writing CSS inside of it:
In this example, we're including styles for the component's container element and a paragraph. Even though we are using generic selectors, the styles don't affect elements with the container class name or <p> tags in other components.
This is an excerpt. The full article is published by Next.js Blog.
Answers to common questions regarding this article's topic, architecture, and practical applications.
Compared to other solutions, being able to adapt the styling of a component based on its props is a big advantage of CSS-in-JS libraries. With Styled JSX we can do so like this: function Alert(props) {
return (
<div className="alert">
{props.children}
<style jsx>{`
.alert {
display: inline-block;
padding: 20px;
border-radius: 8px;
}
`}</style>
<style jsx>{`
.alert
General
A theme can be a simple object where we include the most common variables we might need in our app: const theme = {
fontFamily: {
sansSerif: '-apple-system, "Helvetica Neue", Arial, sans-serif',
mono: 'Menlo, Monaco, monospace',
},
colors: {
text: '#333',
background: '#fff',
link: '#1eaaf1',
linkHover: '#0d8ecf',
border: '#ddd',
warning: '#fff3cd',
success: '#d4edda',
},
};
export default theme;
We th
General
We can also write styles in external files outside of the component. For example, we can move our global styles from the Layout component into a separate file as follows: import css from 'styled-jsx/css';
export default css.global`
body {
margin: 0;
padding: 0;
font-size: 18px;
font-weight: 400;
line-height: 1.8;
color: #333;
font-family: sans-serif;
}
h1 {
font-weight: 700;
}
p {
margin-bottom: 10p
General
Most projects need some global styles to style the body element or provide css resets. Styled JSX allows us to add global styles using <style jsx global>. For example: function Home() {
return (
<div className="container">
<h1>Hello Next.js</h1>
<p>Let's explore different ways to style Next.js apps</p>
<style jsx>{`
.container {
margin: 50px;
}
p {
color: blue;
}
`}
General
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.