Blog>
Snippets

Using Next.js Image Component with Advanced Styling

Showcase advanced styling options for Next.js's built-in Image component for optimized image delivery.
import Image from 'next/image';
import styles from './MyImage.module.css'; // assuming we have CSS modules

export default function MyImage() {
  return (
    <div className={styles.imageContainer}>
      {/* Custom wrapper with relative position for advanced styling */}
      <Image
        src='/path-to-your-image.jpg' // Replace with your image path
        alt='Descriptive text for accessibility'
        layout='fill' // Image will fill the parent container
        objectFit='cover' // Image will cover the area, maintaining aspect ratio
        className={styles.myImage} // Custom style from module CSS
      />
    </div>
  );
}
This code snippet demonstrates the use of the Image component from Next.js with advanced styling options. It uses CSS modules for styling. The Image component is placed inside a custom wrapper with relative positioning, which allows for advanced layout control. `layout='fill'` ensures that the image will fill the dimensions of its parent, and `objectFit='cover'` makes sure the aspect ratio is maintained while covering the available area. Custom styles are applied using `className` from the imported CSS module.