Unverified Commit 5d7b68f1 authored by Alex Castle's avatar Alex Castle Committed by GitHub

Overhaul image component documentation (#29186)

This PR contains an overhaul of the image component documentation for next (both the [primary usage doc](https://nextjs.org/docs/basic-features/image-optimization) and the [API reference](https://nextjs.org/docs/api-reference/next/image)). This PR does not change the filepath/URL for either of those documents, but that may still be warranted as right now Google searches for "next.js image component" and the like return the API document as the first result, which is not optimal.

The changes to the docs are based on feedback from the community and with input from @leerob. I'm marking this PR a draft because we will likely want to have a round of revisions before merging, but in general I consider this PR "read to go," contingent on buy-in from other stakeholders.

The basic goal of the changes are as follows:
1. Simplify the getting started page by moving extraneous detail to the API documentation.
2. Refocus the getting started page on practical usage information
3. Add additional content to address issues that have come up as common pain-points around the image component, such as image sizing and styling.

Fixes #21786 

CC: @styfle @timneutkens @kara @spanicker 
parent 8eec4920
......@@ -24,37 +24,7 @@ description: Enable Image Optimization with the built-in Image component.
</details>
> Before moving forward, we recommend you to read
> [Image Optimization](/docs/basic-features/image-optimization.md) first.
Image Optimization can be enabled via the `<Image />` component exported by
`next/image`.
## Usage
For an example, consider a project with the following files:
- `pages/index.js`
- `public/me.png`
We can serve an optimized image like so:
```jsx
import Image from 'next/image'
import profilePic from '../public/me.png'
function Home() {
return (
<>
<h1>My Homepage</h1>
<Image src={profilePic} alt="Picture of the author" />
<p>Welcome to my homepage!</p>
</>
)
}
export default Home
```
> **Note: This is API documentation for the Image Component and Image Optimization. For a feature overview and usage information for images in Next.js, please see [Images](/docs/basic-features/image-optimization.md).**
## Required Props
......@@ -62,14 +32,14 @@ The `<Image />` component requires the following properties.
### src
Required and must be one of the following:
Must be one of the following:
1. A statically imported image file, as in the example code above, or
1. A [statically imported](/docs/basic-features/image-optimization.md#local-images) image file, or
2. A path string. This can be either an absolute external URL,
or an internal path depending on the [loader](#loader).
When using an external URL, you must add it to
[domains](/docs/basic-features/image-optimization.md#domains) in
[domains](#domains) in
`next.config.js`.
### width
......@@ -86,18 +56,18 @@ Required, except for statically imported images, or those with [`layout="fill"`]
## Optional Props
The `<Image />` component optionally accepts the following properties.
The `<Image />` component accepts a number of additional properties beyond those which are required. This section describes the most commonly-used properties of the Image component. Find details about more rarely-used properties in the [Advanced Props](#advanced-props) section.
### layout
The layout behavior of the image as the viewport changes size.
| `layout` | Behavior | `srcSet` | `sizes` |
| --------------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `intrinsic` (default) | Scale *down* to fit width of container, up to image size | `1x`, `2x` (based on [imageSizes](/docs/basic-features/image-optimization.md#image-sizes)) | N/A |
| `fixed` | Sized to `width` and `height` exactly | `1x`, `2x` (based on [imageSizes](/docs/basic-features/image-optimization.md#image-sizes)) | N/A |
| `responsive` | Scale to fit width of container | `640w`, `750w`, ... `2048w`, `3840w` (based on [imageSizes](/docs/basic-features/image-optimization.md#image-sizes) and [deviceSizes](/docs/basic-features/image-optimization.md#device-sizes)) | `100vw` |
| `fill` | Grow in X and Y axes to fill container | `640w`, `750w`, ... `2048w`, `3840w` (based on [imageSizes](/docs/basic-features/image-optimization.md#image-sizes) and [deviceSizes](/docs/basic-features/image-optimization.md#device-sizes)) | `100vw` |
| `layout` | Behavior | `srcSet` | `sizes` |
| --------------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------- |
| `intrinsic` (default) | Scale *down* to fit width of container, up to image size | `1x`, `2x` (based on [imageSizes](#image-sizes)) | N/A |
| `fixed` | Sized to `width` and `height` exactly | `1x`, `2x` (based on [imageSizes](#image-sizes)) | N/A |
| `responsive` | Scale to fit width of container | `640w`, `750w`, ... `2048w`, `3840w` (based on [imageSizes](#image-sizes) and [deviceSizes](#device-sizes)) | `100vw` |
| `fill` | Grow in both X and Y axes to fill container | `640w`, `750w`, ... `2048w`, `3840w` (based on [imageSizes](#image-sizes) and [deviceSizes](#device-sizes)) | `100vw` |
- [Demo the `intrinsic` layout (default)](https://image-component.nextjs.gallery/layout-intrinsic)
- When `intrinsic`, the image will scale the dimensions down for smaller viewports, but maintain the original dimensions for larger viewports.
......@@ -114,14 +84,16 @@ The layout behavior of the image as the viewport changes size.
### loader
A custom function used to resolve URLs. Defaults to [`images` object in `next.config.js`](/docs/basic-features/image-optimization.md#loader).
A custom function used to resolve URLs. Setting the loader as a prop on the Image component overrides the default loader defined in the [`images` section of `next.config.js`](#loader-configuration).
`loader` is a function returning a string, given the following parameters:
A `loader` is a function returning a URL string for the image, given the following parameters:
- [`src`](#src)
- [`width`](#width)
- [`quality`](#quality)
Here is an example of using a custom loader with `next/image`:
```js
import Image from 'next/image'
......@@ -144,30 +116,32 @@ const MyImage = (props) => {
### sizes
A string mapping media queries to device sizes. Defaults to `100vw`.
A string that provides information about how wide the image will be at different breakpoints. Defaults to `100vw` (the full width of the screen) when using `layout="responsive"` or `layout="fill"`.
`sizes` is important for performance when using `layout="responsive"` or `layout="fill"` with images that take up less than the full viewport width.
We recommend setting `sizes` when using `layout="responsive"` or `layout="fill"` and your image will **not** be the same width as the viewport.
If you are using `layout="fill"` or `layout="responsive"` and the image will always be less than half the viewport width, include `sizes="50vw"`. Without `sizes`, the image will be sent at twice the necessary resolution, decreasing performance.
[Learn more](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-sizes).
### quality
The quality of the optimized image, an integer between `1` and `100` where `100`
is the best quality. Defaults to `75`.
The quality of the optimized image, an integer between `1` and `100` where `100` is the best quality. Defaults to `75`.
### priority
When true, the image will be considered high priority and
[preload](https://web.dev/preload-responsive-images/).
[preload](https://web.dev/preload-responsive-images/). Lazy loading is automatically disabled for images using `priority`.
Should only be used when the image is visible above the fold. Defaults to
`false`.
You should use the `priority` attribute on any image which you suspect will be the [Largest Contentful Paint (LCP) element](https://nextjs.org/learn/seo/web-performance/lcp). It may be appropriate to have multiple priority images, as different images may be the LCP element for different viewport sizes.
Should only be used when the image is visible above the fold. Defaults to `false`.
### placeholder
A placeholder to use while the image is loading, possible values are `blur` or `empty`. Defaults to `empty`.
A placeholder to use while the image is loading. Possible values are `blur` or `empty`. Defaults to `empty`.
When `blur`, the [`blurDataURL`](#blurdataurl) property will be used as the placeholder. If `src` is an object from a static import and the imported image is jpg, png, or webp, then `blurDataURL` will automatically be populated.
When `blur`, the [`blurDataURL`](#blurdataurl) property will be used as the placeholder. If `src` is an object from a [static import](#local-images) and the imported image is `.jpg`, `.png`, or `.webp`, then `blurDataURL` will be automatically populated.
For dynamic images, you must provide the [`blurDataURL`](#blurdataurl) property. Solutions such as [Plaiceholder](https://github.com/joe-bell/plaiceholder) can help with `base64` generation.
......@@ -180,20 +154,19 @@ Try it out:
## Advanced Props
In some cases, you may need more advanced usage. The `<Image />` component
optionally accepts the following advanced properties.
In some cases, you may need more advanced usage. The `<Image />` component optionally accepts the following advanced properties.
### objectFit
The image fit when using `layout="fill"`.
Defines how the image will fit into its parent container when using `layout="fill"`.
[Learn more](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)
This value is passed to the [object-fit CSS property](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) for the `src` image.
### objectPosition
The image position when using `layout="fill"`.
Defines how the image is positioned within its parent element when using `layout="fill"`.
[Learn more](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position)
This value is passed to the [object-position CSS property](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) applied to the image.
### onLoadingComplete
......@@ -255,26 +228,136 @@ Other properties on the `<Image />` component will be passed to the underlying
- `style`. Use `className` instead.
- `srcSet`. Use
[Device Sizes](/docs/basic-features/image-optimization.md#device-sizes)
[Device Sizes](#device-sizes)
instead.
- `ref`. Use [`onLoadingComplete`](#onloadingcomplete) instead.
- `decoding`. It is always `"async"`.
## Styling
## Configuration Options
### Domains
To protect your application from malicious users, you must define a list of image provider domains that you want to be served from the Next.js Image Optimization API. This is configured in with the `domains` property in your `next.config.js` file, as shown below:
```js
module.exports = {
images: {
domains: ['assets.acme.com'],
},
}
```
### Loader Configuration
If you want to use a cloud provider to optimize images instead of using the Next.js built-in Image Optimization API, you can configure the `loader` and `path` prefix in your `next.config.js` file. This allows you to use relative URLs for the Image `src` and automatically generate the correct absolute URL for your provider.
```js
module.exports = {
images: {
loader: 'imgix',
path: 'https://example.com/myaccount/',
},
}
```
### Built-in Loaders
The following Image Optimization cloud providers are included:
- Default: Works automatically with `next dev`, `next start`, or a custom server
- [Vercel](https://vercel.com): Works automatically when you deploy on Vercel, no configuration necessary. [Learn more](https://vercel.com/docs/next.js/image-optimization)
- [Imgix](https://www.imgix.com): `loader: 'imgix'`
- [Cloudinary](https://cloudinary.com): `loader: 'cloudinary'`
- [Akamai](https://www.akamai.com): `loader: 'akamai'`
- Custom: `loader: 'custom'` use a custom cloud provider by implementing the [`loader`](/docs/api-reference/next/image.md#loader) prop on the `next/image` component
If you need a different provider, you can use the [`loader`](#loader) prop with `next/image`.
> The `next/image` component's default loader is not supported when using [`next export`](/docs/advanced-features/static-html-export.md). However, other loader options will work.
> The `next/image` component's default loader uses [`squoosh`](https://www.npmjs.com/package/@squoosh/lib) because it is quick to install and suitable for a development environment. When using `next start` in your production environment, it is strongly recommended that you install [`sharp`](https://www.npmjs.com/package/sharp) by running `yarn add sharp` in your project directory. This is not necessary for Vercel deployments, as `sharp` is installed automatically.
`next/image` wraps the `img` element with a single `div` element to maintain the aspect ratio of the image and prevent [Cumulative Layout Shift](https://vercel.com/blog/core-web-vitals#cumulative-layout-shift).
## Advanced
To add styles to the underlying `img` element, pass the `className` prop to the `<Image />` component. Then, use Next.js' [built-in CSS support](/docs/basic-features/built-in-css-support.md) to add rules to that class.
The following configuration is for advanced use cases and is usually not necessary. If you choose to configure the properties below, you will override any changes to the Next.js defaults in future updates.
**Note:** If using [`layout="fill"`](/docs/api-reference/next/image.md#layout), ensure the parent element uses `position: relative`.
### Device Sizes
If you know the expected device widths of your users, you can specify a list of device width breakpoints using the `deviceSizes` property in `next.config.js`. These widths are used when the [`next/image`](/docs/api-reference/next/image.md) component uses `layout="responsive"` or `layout="fill"` to ensure the correct image is served for user's device.
If no configuration is provided, the default below is used.
```js
module.exports = {
images: {
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
},
}
```
### Image Sizes
You can specify a list of image widths using the `images.imageSizes` property in your `next.config.js` file. These widths are concatenated with the array of [device sizes](#device-sizes) to form the full array of sizes used to generate image [srcset](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/srcset)s.
The reason there are two seperate lists is that imageSizes is only used for images which provide a [`sizes`](#sizes) prop, which indicates that the image is less than the full width of the screen. **Therefore, the sizes in imageSizes should all be smaller than the smallest size in deviceSizes.**
If no configuration is provided, the default below is used.
```js
module.exports = {
images: {
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
},
}
```
## Caching Behavior
The following describes the caching algorithm for the default [loader](#loader). For all other loaders, please refer to your cloud provider's documentation.
Images are optimized dynamically upon request and stored in the `<distDir>/cache/images` directory. The optimized image file will be served for subsequent requests until the expiration is reached. When a request is made that matches a cached but expired file, the cached file is deleted before generating a new optimized image and caching the new file.
The expiration (or rather Max Age) is defined by the upstream server's `Cache-Control` header.
- If `s-maxage` is found in `Cache-Control`, it is used. If no `s-maxage` is found, then `max-age` is used. If no `max-age` is found, then [`minimumCacheTTL`](#minimum-cache-ttl) is used.
- You can configure [`minimumCacheTTL`](#minimum-cache-ttl) to increase the cache duration when the upstream image does not include `max-age`.
- You can also configure [`deviceSizes`](#device-sizes) and [`imageSizes`](#device-sizes) to reduce the total number of possible generated images.
You can configure the Time to Live (TTL) in seconds for cached optimized images. In many cases, it's better to use a [Static Image Import](/docs/basic-features/image-optimization.md#local-images) which will automatically hash the file contents and cache the image forever with a `Cache-Control` header of `immutable`.
```js
module.exports = {
images: {
minimumCacheTTL: 60,
},
}
```
If you need to add a `Cache-Control` header for the browser (not recommended), you can configure [`headers`](/docs/api-reference/next.config.js/headers) on the upstream image e.g. `/some-asset.jpg` not `/_next/image` itself.
### Disable Static Imports
The default behavior allows you to import static files such as `import icon from './icon.png` and then pass that to the `src` property.
In some cases, you may wish to disable this feature if it conflicts with other plugins that expect the import to behave differently.
You can disable static image imports inside your `next.config.js`:
```js
module.exports = {
images: {
disableStaticImages: true,
},
}
```
## Related
For more information on what to do next, we recommend the following sections:
For an overview of the Image component features and usage guidelines, see:
<div class="card">
<a href="/docs/basic-features/image-optimization.md">
<b>Image Optimization</b>
<small>See how to configure domains and loaders.</small>
<b>Images</b>
<small>Learn how to display and optimize images with the Image component.</small>
</a>
</div>
......@@ -11,66 +11,75 @@ description: Next.js supports built-in image optimization, as well as third part
</ul>
</details>
Since version **10.0.0**, Next.js has a built-in Image Component and Automatic Image Optimization.
The Next.js Image component, [`next/image`](/docs/api-reference/next/image.md), is an extension of the HTML `<img>` element, evolved for the modern web. It includes a variety of built-in performance optimizations to help you achieve good [Core Web Vitals](https://nextjs.org/learn/seo/web-performance). These scores are an important measurement of user experience on your website, and are [factored into Google's search rankings](https://nextjs.org/learn/seo/web-performance/seo-impact).
The Next.js Image Component, [`next/image`](/docs/api-reference/next/image.md), is an extension of the HTML `<img>` element, evolved for the modern web.
Some of the optimizations built into the Image component include:
The Automatic Image Optimization allows for resizing, optimizing, and serving images in modern formats like [WebP](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types) when the browser supports it. This avoids shipping large images to devices with a smaller viewport. It also allows Next.js to automatically adopt future image formats and serve them to browsers that support those formats.
- **Improved Performance:** Always serve correctly sized image for each device, using modern image formats.
- **Visual Stability:** Prevent [Cumulative Layout Shift](https://nextjs.org/learn/seo/web-performance/cls) automatically.
- **Faster Page Loads:** Images are only loaded when they enter the viewport, with optional blur-up placeholders
- **Asset Flexibility:** On-demand image resizing, even for images stored on remote servers
Automatic Image Optimization works with any image source. Even if the image is hosted by an external data source, like a CMS, it can still be optimized.
## Using the Image Component
Instead of optimizing images at build time, Next.js optimizes images on-demand, as users request them. Unlike static site generators and static-only solutions, your build times aren't increased, whether shipping 10 images or 10 million images.
To add an image to your application, import the [`next/image`](/docs/api-reference/next/image.md) component:
Images are lazy loaded by default. That means your page speed isn't penalized for images outside the viewport. Images load as they are scrolled into viewport.
```jsx
import Image from 'next/image'
```
Images are always rendered in such a way as to avoid [Cumulative Layout Shift](https://web.dev/cls/), a [Core Web Vital](https://web.dev/vitals/) that Google [uses in search ranking](https://developers.google.com/search/blog/2020/05/evaluating-page-experience).
Now, you can define the `src` for your image (either local or remote).
## Image Component
### Local Images
To add an image to your application, import the [`next/image`](/docs/api-reference/next/image.md) component:
To use a local image, `import` your `.jpg`, `.png`, or `.webp` files:
```jsx
import profilePic from '../public/me.png'
```
Dynamic `await import()` or `require()` are _not_ supported. The `import` must be static. Also note that static image support requires Webpack 5, which is enabled by default in Next.js applications.
Next.js will automatically determine the `width` and `height` or your image based on the imported file. These values are used to prevent [Cumulative Layout Shift](https://nextjs.org/learn/seo/web-performance/cls) while your image is loading.
```js
import Image from 'next/image'
import profilePic from '../public/me.png'
function Home() {
return (
<>
<h1>My Homepage</h1>
<Image
src="/me.png"
src={profilePic}
alt="Picture of the author"
width={500}
height={500}
// width={500} automatically provided
// height={500} automatically provided
// blurDataURL="data:..." automatically provided
// placeholder="blur" // Optional blur-up while loading
/>
<p>Welcome to my homepage!</p>
</>
)
}
export default Home
```
## Image Imports
You can statically `import` images that live in your project. Dynamic `await import()` or `require()` are _not_ supported.
### Remote Images
With static `import`s, you only need to provide the `src` prop. The `width`, `height`, and `blurDataURL` props will automatically be populated. Alt text is still needed separately.
To use a remote image, the `src` property should be a URL string, which can be [relative](#loaders) or [absolute](#domains). Because Next.js does not have access to remote files during the build process, you'll need to provide the [`width`](/docs/api-reference/next/image.md#width), [`height`](/docs/api-reference/next/image.md#height) and optional [`blurDataURL`](/docs/api-reference/next/image.md#blurdataurl) props manually:
```js
```jsx
import Image from 'next/image'
import profilePic from '../public/me.png'
function Home() {
export default function Home() {
return (
<>
<h1>My Homepage</h1>
<Image
src={profilePic}
src="/me.png"
alt="Picture of the author"
// width={500} automatically provided
// height={500} automatically provided
// blurDataURL="data:..." automatically provided
// placeholder="blur" // Optional blur-up while loading
width={500}
height={500}
/>
<p>Welcome to my homepage!</p>
</>
......@@ -78,132 +87,101 @@ function Home() {
}
```
For remote images, you'll need to provide the [`width`](/docs/api-reference/next/image.md#width), [`height`](/docs/api-reference/next/image.md#height) and [`blurDataURL`](/docs/api-reference/next/image.md#blurdataurl) props manually.
## Properties
[View all properties](/docs/api-reference/next/image.md) available to the `next/image` component.
## Configuration
In addition to [using properties](/docs/api-reference/next/image.md) available to the `next/image` component, you can optionally configure Image Optimization for more advanced use cases via `next.config.js`.
> Learn more about the [sizing requirements](#image-sizing) in `next/image`.
### Domains
To enable Image Optimization for images hosted on an external website, use an absolute url for the Image `src` and specify which
`domains` are allowed to be optimized. This is needed to ensure that external urls can't be abused. When `loader` is set to an external image service, this option is ignored.
```js
module.exports = {
images: {
domains: ['example.com'],
},
}
```
### Loader
Sometimes you may want to access a remote image, but still use the built-in Next.js Image Optimization API. To do this, leave the `loader` at its default setting and enter an absolute URL for the Image `src`.
If you want to use a cloud provider to optimize images instead of using the Next.js' built-in Image Optimization, you can configure the loader and path prefix. This allows you to use relative urls for the Image `src` and automatically generate the correct absolute url for your provider.
To protect your application from malicious users, you must define a list of remote domains that you intend to access this way. This is configured in your `next.config.js` file, as shown below:
```js
module.exports = {
images: {
loader: 'imgix',
path: 'https://example.com/myaccount/',
domains: ['example.com', 'example2.com'],
},
}
```
The following Image Optimization cloud providers are included:
### Loaders
- [Vercel](https://vercel.com): Works automatically when you deploy on Vercel, no configuration necessary. [Learn more](https://vercel.com/docs/next.js/image-optimization)
- [Imgix](https://www.imgix.com): `loader: 'imgix'`
- [Cloudinary](https://cloudinary.com): `loader: 'cloudinary'`
- [Akamai](https://www.akamai.com): `loader: 'akamai'`
- Custom: `loader: 'custom'` use a custom cloud provider by implementing the [`loader`](/docs/api-reference/next/image.md#loader) prop on the `next/image` component
- Default: Works automatically with `next dev`, `next start`, or a custom server
Note that in the [example earlier](#remote-images), a partial URL (`"/me.png"`) is provided for a remote image. This is possible because of the `next/image` [loader](/docs/api-reference/next/image.md#loader) architecture.
If you need a different provider, you can use the [`loader`](/docs/api-reference/next/image.md#loader) prop with `next/image`.
A loader is a function that generates the URLs for your image. It appends a root domain to your provided `src`, and generates multiple URLs to request the image at different sizes. These multiple URLs are used in the automatic [srcset](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/srcset) generation, so that visitors to your site will be served an image that is the right size for their viewport.
> The `next/image` component's default loader is not supported when using [`next export`](/docs/advanced-features/static-html-export.md). However, other loader options will work.
The default loader for Next.js applications uses the built-in Image Optimization API, which optimizes images from anywhere on the web, and then serves them directly from the Next.js web server. If you would like to serve your images directly from a CDN or image server, you can use one of the [built-in loaders](/docs/api-reference/next/image.md#built-in-loaders) or write your own with a few lines of JavaScript.
> The `next/image` component's default loader uses [`squoosh`](https://www.npmjs.com/package/@squoosh/lib) because it is quick to install and suitable for a development environment. When using `next start` in your production environment, it is strongly recommended that you install [`sharp`](https://www.npmjs.com/package/sharp) by running `yarn add sharp` in your project directory. This is not necessary for Vercel deployments, as `sharp` is installed automatically.
Loaders can be defined per-image, or at the application level.
## Caching
## Image Sizing
The following describes the caching algorithm for the default [loader](#loader). For all other loaders, please refer to your cloud provider's documentation.
One of the ways that images most commonly hurt performance is through _layout shift_, where the image pushes other elements around on the page as it loads in. This performance problem is so annoying to users that it has its own Core Web Vital, called [Cumulative Layout Shift](https://web.dev/cls/). The way to avoid image-based layout shifts is to [always size your images](https://web.dev/optimize-cls/#images-without-dimensions). This allows the browser to reserve precisely enough space for the image before it loads.
Images are optimized dynamically upon request and stored in the `<distDir>/cache/images` directory. The optimized image file will be served for subsequent requests until the expiration is reached. When a request is made that matches a cached but expired file, the cached file is deleted before generating a new optimized image and caching the new file.
Because `next/image` is designed to guarantee good performance results, it cannot be used in a way that will contribute to layout shift, and **must** be sized in one of three ways:
The expiration (or rather Max Age) is defined by the upstream server's `Cache-Control` header.
1. Automatically, using a [static import](#local-images)
2. Explicitly, by including a `height` **and** `width` property
3. Implicitly, by using `layout="fill"` which causes the image to expand to fill its parent element.
If `s-maxage` is found in `Cache-Control`, it is used. If no `s-maxage` is found, then `max-age` is used. If no `max-age` is found, then [`minimumCacheTTL`](#minimum-cache-ttl) is used.
> ### What if I don't know the size of my images?
>
> If you are accessing images from a source without knowledge of the images' sizes, there are several things you can do:
>
> **Use `layout='fill'`**
>
> The `fill` layout mode allows your image to be sized by its parent element. Consider using CSS to give the image's parent element space on the page, then using the [`objectFit property`](/docs/api-reference/next/image.md#objectfit) with `fill`, `contain`, or `cover`, along with the [`objectPosition property`](/docs/api-reference/next/image.md#objectposition) to define how the image should occupy that space.
>
> **Normalize your images**
>
> If you're serving images from a source that you control, consider modifying your image pipeline to normalize the images to a specific size.
>
> **Modify your API calls**
>
> If your application is retrieving image URLs using an API call (such as to a CMS), you may be able to modify the API call to return the image dimensions along with the URL.
You can configure [`minimumCacheTTL`](#minimum-cache-ttl) to increase the cache duration when the upstream image does not include `max-age`.
If none of the suggested methods works for sizing your images, the `next/image` component is designed to work well on a page alongside standard `<img>` elements.
You can also configure [`deviceSizes`](#device-sizes) and [`imageSizes`](#device-sizes) to reduce the total number of possible generated images.
## Styling
## Advanced
Styling the Image component is not that different from styling a normal `<img>` element, but there are a few guidelines to keep in mind:
The following configuration is for advanced use cases and is usually not necessary. If you choose to configure the properties below, you will override any changes to the Next.js defaults in future updates.
**Pick the correct layout mode**
### Device Sizes
The image component has several different [layout modes](/docs/api-reference/next/image.md#layout) that define how it is sized on the page. If the styling of your image isn't turning out the way you want, consider experimenting with other layout modes.
In some cases, where you know the expected device widths from the users of your website, you can specify a list of device width breakpoints using the `deviceSizes` property. These widths are used when the [`next/image`](/docs/api-reference/next/image.md) component uses `layout="responsive"` or `layout="fill"` so that the correct image is served for the device visiting your website.
**Target the image with className, not based on DOM structure**
If no configuration is provided, the default below is used.
Regardless of the layout mode used, the Image component will have a consistent DOM structure of one `<img>` tag wrapped by exactly one `<div>`. For some modes, it may also have a sibling `<div>` for spacing. These additional `<div>` elements are critical to allow the component to prevent layout shifts.
```js
module.exports = {
images: {
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
},
}
```
The recommended way to style the inner `<img>` is to set the `className` prop on the Image component to the value of an imported [CSS Module](/docs/basic-features/built-in-css-support.md#adding-component-level-css). The value of `className` will be automatically applied to the underlying `<img>` element.
### Image Sizes
Alternatively, you can import a [global stylesheet](/docs/basic-features/built-in-css-support#adding-a-global-stylesheet) and manually set the `className` prop to the same name used in the global stylesheet.
You can specify a list of image widths using the `imageSizes` property. These widths should be different (usually smaller) than the widths defined in `deviceSizes` because the arrays will be concatenated. These widths are used when the [`next/image`](/docs/api-reference/next/image.md) component uses `layout="fixed"` or `layout="intrinsic"`.
You cannot use [styled-jsx](/basic-features/built-in-css-support.md#css-in-js) because its scoped to the current component.
If no configuration is provided, the default below is used.
You cannot use the `style` prop because the `<Image>` component does not pass it through to the underlying `<img>`.
```js
module.exports = {
images: {
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
},
}
```
**When using `layout='fill'`, the parent element must have `position: relative`**
### Minimum Cache TTL
This is necessary for the proper rendering of the image element in that layout mode.
You can configure the time to live (TTL) in seconds for cached optimized images. In many cases, its better to use a [Static Image Import](#image-Imports) which will handle hashing file contents and caching the file forever.
**When using `layout='responsive'`, the parent element must have `display: block`**
```js
module.exports = {
images: {
minimumCacheTTL: 60,
},
}
```
This is the default for `<div>` elements but should be specified otherwise.
If you need to add a `Cache-Control` header for the browser (not recommended), you can configure [`headers`](/docs/api-reference/next.config.js/headers) on the upstream image e.g. `/some-asset.jpg` not `/_next/image` itself.
## Properties
### Disable Static Imports
[**View all properties available to the `next/image` component.**](/docs/api-reference/next/image.md)
The default behavior allows you to import static files such as `import icon from './icon.png` and then pass that to the `src` property.
### Styling Examples
In some cases, you may wish to disable this feature if it conflicts with other plugins that expect the import to behave differently.
For examples of the Image component used with the various fill modes, see the [Image component example app](https://image-component.nextjs.gallery/).
You can disable static image imports with the following configuration below.
## Configuration
```js
module.exports = {
images: {
disableStaticImages: true,
},
}
```
The `next/image` component and Next.js Image Optimization API can be configured in the [`next.config.js` file](/docs/api-reference/next.config.js/introduction.md). These configurations allow you to [enable remote domains](/docs/api-reference/next/image.md#domains), [define custom image breakpoints](/docs/api-reference/next/image.md#device-sizes), [change caching behavior](/docs/api-reference/next/image.md#caching-behavior) and more.
[**Read the full image configuration documentation for more information.**](/docs/api-reference/next/image.md#configuration-options)
## Related
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment