Styling in Next.js offers flexibility, and you can choose from various approaches.
There exist 2 popular approach.
CSS-in-JS with styled-components and traditional CSS with CSS modules
1.CSS-in-JS with Styled-Components:
// components/Button.js
import styled from ‘styled-components’;
const StyledButton = styled.button`
padding: 10px 15px;
font-size: 16px;
color: white;
background-color: ${(props) => (props.primary ? ‘blue’ : ‘green’)};
border: none;
border-radius: 5px;
cursor: pointer;
&:hover {
background-color: ${(props) => (props.primary ? ‘darkblue’ : ‘darkgreen’)};
}
`;
const Button = ({ children, primary }) => {
return {children};
};
export default Button;
We’ve created a reusable Button component styled with styled-components in this example. It accepts a primary prop to determine the color scheme.
2. Traditional CSS with CSS Modules:
// components/Card.module.css
.card {
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
margin: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.title {
font-size: 18px;
color: #333;
}
// components/Card.js
import React from ‘react’;
import styles from ‘./Card.module.css’;
const Card = ({ title, children }) => {
return (
{title}
{children}
);
};
export default Card;
Here, we’ve used CSS modules for styling. The styles are scoped to the component, preventing global style conflicts.
These examples demonstrate the versatility of styling in Next.js, allowing you to choose the approach that best fits your preferences and project requirements.