Blog>
Snippets

Styling MDX Content with CSS Modules in Next.js

Detailing how to apply CSS Modules to style MDX content in a Next.js application, ensuring scope is limited to the component.
// styles/MDXComponent.module.css
.paraStyle {
  color: #333;
  font-size: 18px;
  line-height: 1.6;
}

.headingStyle {
  color: #0056b3;
  margin-top: 20px;
}
This is a CSS module file for styling a specific MDX component, defining styles for paragraph `.paraStyle` and heading `.headingStyle`. The scope is limited to the component that imports it.
import styles from './styles/MDXComponent.module.css';

export default function MDXComponent() {
  // More component logic here...

  return (
    <>
      <h1 className={styles.headingStyle}>Heading styled with CSS Module</h1>
      <p className={styles.paraStyle}>This is a paragraph styled by a CSS Module.</p>
    </>
  );
}
This is a React component in a Next.js application that imports the CSS module and applies the defined styles to specific JSX elements, ensuring that the styles are scoped to this component only.
// next.config.js
const withMDX = require('@next/mdx')({
  extension: /\.mdx?$/',
})

module.exports = withMDX({
  pageExtensions: ['js', 'jsx', 'md', 'mdx'],
});
This configuration in `next.config.js` enables MDX support in a Next.js application, allowing `.md` and `.mdx` files to be pages.
import MDXComponent from '../components/MDXComponent';

export const getStaticProps = async () => {
  // Fetch or compile MDX content here...
  const mdxContent = '...';
  return { props: { mdxContent } };
};

export default function MDXPage({ mdxContent }) {
  return <MDXComponent>{mdxContent}</MDXComponent>;
}
This is an example of a Next.js page that uses getStaticProps to fetch or compile MDX content (could be from a local file or external source) and passes it to an MDXComponent, which will render the content using the styles defined in the CSS module.