Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .changeset/shaky-coins-fry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'astro': patch
---

Simplifies styles for experimental responsive images

:warning: **BREAKING CHANGE FOR EXPERIMENTAL RESPONSIVE IMAGES ONLY** :warning:

The generated styles for image layouts are now simpler and easier to override. Previously it used CSS to set the size and aspect ratio of the images, but this is no longer needed. Now it just sets `object-fit` and `object-position`, and sets `max-width: 100%` for constrained images and `width: 100%` for full-width images.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great explanation of what's happening! My only nit is not being super clear on what "it" is referring to. (If it's "generated styles" then should be "they" for plural? If it's "layouts" that's also plural unless you just want to say "your layout used CSS". If it's Astro, then we haven't introduced that antecedent at all yet!)

Not a huge deal, but enough that I went, "wait a minute, what is "it" here?" so might be enough to be a bit distracting to readers.

Also, there's little guidance here as to what to do about this breaking change (if anything?). We could add something after this paragraph as another standalone paragraph so it stands out, like:

This is an implementation change only. However, it may affect any custom styles you have added to your responsive images. Please check your rendered images to determine whether any change to your CSS is needed.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about now


The styles now use the [`:where()` pseudo-class](https://developer.mozilla.org/en-US/docs/Web/CSS/:where), which has a [specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_cascade/Specificity) of 0, meaning that it is easy to override with your own styles. You can now be sure that your own classes will always override the applied styles, as will global styles on `img`.

An exception is Tailwind 4, which uses [cascade layers](https://developer.mozilla.org/en-US/docs/Web/CSS/@layer), meaning the rules are always lower specificity. Astro supports browsers that do not support cascade layers, so we cannot use this. If you need to override the styles using Tailwind 4, you must use `!important` classes. Do check if this is needed though: there may be a layout that is more appropriate for your use case.
38 changes: 38 additions & 0 deletions .changeset/tall-pots-fly.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
---
'astro': patch
---

Renames experimental responsive image layout option from "responsive" to "constrained"

:warning: **BREAKING CHANGE FOR EXPERIMENTAL RESPONSIVE IMAGES ONLY** :warning:

The layout option called `"responsive"` is renamed to `"constrained"` to better reflect its behavior.

The previous name was causing confusion, because it is also the name of the feature. The `responsive` layout option is specifically for images that are displayed at the requested size, unless they do not fit the width of their container, at which point they would be scaled down to fit. They do not get scaled beyond the intrinsic size of the source image, or the `width` prop if provided.

It became clear from user feedback that many people (understandably) thought that they needed to set `layout` to `responsive` if they wanted to use responsive images. They then struggled with overriding styles to make the image scale up for full-width hero images, for example, when they should have been using `full-width` layout. Renaming the layout to `constrained` should make it clearer that this layout is for when you want to constrain the maximum size of the image, but allow it to scale-down.

### Upgrading

If you set a default `image.experimentalLayout` in your `astro.config.mjs`, or set it on a per-image basis using the `layout` prop, you will need to change all occurences to `constrained`:

```diff lang="ts"
// astro.config.mjs
export default {
image: {
- experimentalLayout: 'responsive',
+ experimentalLayout: 'constrained',
},
}
```

```diff lang="astro"
// src/pages/index.astro
---
import { Image } from 'astro:assets';
---
- <Image src="/image.jpg" layout="responsive" />
+ <Image src="/image.jpg" layout="constrained" />
```

Please [give feedback on the RFC](https://github.com/withastro/roadmap/pull/1051) if you have any questions or comments about the responsive images API.
17 changes: 5 additions & 12 deletions packages/astro/components/image.css
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
[data-astro-image] {
width: 100%;
height: auto;
:where([data-astro-image]) {
object-fit: var(--fit);
object-position: var(--pos);
aspect-ratio: var(--w) / var(--h);
}
/* Styles for responsive layout */
[data-astro-image='responsive'] {
max-width: calc(var(--w) * 1px);
max-height: calc(var(--h) * 1px);
:where([data-astro-image='full-width']) {
width: 100%;
}
/* Styles for fixed layout */
[data-astro-image='fixed'] {
width: calc(var(--w) * 1px);
height: calc(var(--h) * 1px);
:where([data-astro-image='constrained']) {
max-width: 100%;
}
2 changes: 0 additions & 2 deletions packages/astro/src/assets/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,6 @@ export async function getImage(
if (layout !== 'none') {
resolvedOptions.style = addCSSVarsToStyle(
{
w: String(resolvedOptions.width),
h: String(resolvedOptions.height),
fit: cssFitValues.includes(resolvedOptions.fit ?? '') && resolvedOptions.fit,
pos: resolvedOptions.position,
},
Expand Down
10 changes: 5 additions & 5 deletions packages/astro/src/assets/layout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ export const getWidths = ({
return originalWidth && width > originalWidth ? [originalWidth] : [width, maxSize];
}

// For responsive layout we want to return all breakpoints smaller than 2x requested width.
if (layout === 'responsive') {
// For constrained layout we want to return all breakpoints smaller than 2x requested width.
if (layout === 'constrained') {
return (
[
// Always include the image at 1x and 2x the specified width
Expand Down Expand Up @@ -100,15 +100,15 @@ export const getSizesAttribute = ({
switch (layout) {
// If screen is wider than the max size then image width is the max size,
// otherwise it's the width of the screen
case `responsive`:
case "constrained":
return `(min-width: ${width}px) ${width}px, 100vw`;

// Image is always the same width, whatever the size of the screen
case `fixed`:
case "fixed":
return `${width}px`;

// Image is always the width of the screen
case `full-width`:
case "full-width":
return `100vw`;

case 'none':
Expand Down
8 changes: 4 additions & 4 deletions packages/astro/src/assets/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export type ImageQualityPreset = 'low' | 'mid' | 'high' | 'max' | (string & {});
export type ImageQuality = ImageQualityPreset | number;
export type ImageInputFormat = (typeof VALID_INPUT_FORMATS)[number];
export type ImageOutputFormat = (typeof VALID_OUTPUT_FORMATS)[number] | (string & {});
export type ImageLayout = 'responsive' | 'fixed' | 'full-width' | 'none';
export type ImageLayout = 'constrained' | 'fixed' | 'full-width' | 'none';
export type ImageFit = 'fill' | 'contain' | 'cover' | 'none' | 'scale-down' | (string & {});

export type AssetsGlobalStaticImagesList = Map<
Expand Down Expand Up @@ -162,15 +162,15 @@ type ImageSharedProps<T> = T & {
/**
* The layout type for responsive images. Requires the `experimental.responsiveImages` flag to be enabled in the Astro config.
*
* Allowed values are `responsive`, `fixed`, `full-width` or `none`. Defaults to value of `image.experimentalLayout`.
* Allowed values are `constrained`, `fixed`, `full-width` or `none`. Defaults to value of `image.experimentalLayout`.
*
* - `responsive` - The image will scale to fit the container, maintaining its aspect ratio, but will not exceed the specified dimensions.
* - `constrained` - The image will scale to fit the container, maintaining its aspect ratio, but will not exceed the specified dimensions.
* - `fixed` - The image will maintain its original dimensions.
* - `full-width` - The image will scale to fit the container, maintaining its aspect ratio, even if that means the image will exceed its original dimensions.
*
* **Example**:
* ```astro
* <Image src={...} layout="responsive" alt="..." />
* <Image src={...} layout="constrained" alt="..." />
* ```
*/

Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/config/schemas/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ export const AstroConfigSchema = z.object({
}),
)
.default([]),
experimentalLayout: z.enum(['responsive', 'fixed', 'full-width', 'none']).optional(),
experimentalLayout: z.enum(['constrained', 'fixed', 'full-width', 'none']).optional(),
experimentalObjectFit: z.string().optional(),
experimentalObjectPosition: z.string().optional(),
experimentalBreakpoints: z.array(z.number()).optional(),
Expand Down
41 changes: 19 additions & 22 deletions packages/astro/src/types/public/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1331,7 +1331,7 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
* @description
* The default layout type for responsive images. Can be overridden by the `layout` prop on the image component.
* Requires the `experimental.responsiveImages` flag to be enabled.
* - `responsive` - The image will scale to fit the container, maintaining its aspect ratio, but will not exceed the specified dimensions.
* - `constrained` - The image will scale to fit the container, maintaining its aspect ratio, but will not exceed the specified dimensions.
* - `fixed` - The image will maintain its original dimensions.
* - `full-width` - The image will scale to fit the container, maintaining its aspect ratio.
*/
Expand Down Expand Up @@ -2096,14 +2096,14 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
* }
* ```
*
* When enabled, you can pass a `layout` props to any `<Image />` or `<Picture />` component to create a responsive image. When a layout is set, images have automatically generated `srcset` and `sizes` attributes based on the image's dimensions and the layout type. Images with `responsive` and `full-width` layouts will have styles applied to ensure they resize according to their container.
* When enabled, you can pass a `layout` props to any `<Image />` or `<Picture />` component to create a responsive image. When a layout is set, images have automatically generated `srcset` and `sizes` attributes based on the image's dimensions and the layout type. Images with `constrained` and `full-width` layouts will have styles applied to ensure they resize according to their container.
*
* ```astro title=MyComponent.astro
* ---
* import { Image, Picture } from 'astro:assets';
* import myImage from '../assets/my_image.png';
* ---
* <Image src={myImage} alt="A description of my image." layout='responsive' width={800} height={600} />
* <Image src={myImage} alt="A description of my image." layout='constrained' width={800} height={600} />
* <Picture src={myImage} alt="A description of my image." layout='full-width' formats={['avif', 'webp', 'jpeg']} />
* ```
* This `<Image />` component will generate the following HTML output:
Expand All @@ -2125,31 +2125,28 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
* fetchpriority="auto"
* width="800"
* height="600"
* style="--w: 800; --h: 600; --fit: cover; --pos: center;"
* data-astro-image="responsive"
* style="--fit: cover; --pos: center;"
* data-astro-image="constrained"
* >
* ```
*
* The following styles are applied to ensure the images resize correctly:
*
* ```css title="Responsive Image Styles"
* [data-astro-image] {
* width: 100%;
* height: auto;
* object-fit: var(--fit);
* object-position: var(--pos);
* aspect-ratio: var(--w) / var(--h)
*
* :where([data-astro-image]) {
* object-fit: var(--fit);
* object-position: var(--pos);
* }
*
* [data-astro-image=responsive] {
* max-width: calc(var(--w) * 1px);
* max-height: calc(var(--h) * 1px)
*
* :where([data-astro-image='full-width']) {
* width: 100%;
* }
*
* [data-astro-image=fixed] {
* width: calc(var(--w) * 1px);
* height: calc(var(--h) * 1px)
*
* :where([data-astro-image='constrained']) {
* max-width: 100%;
* }
*
* ```
* You can enable responsive images for all `<Image />` and `<Picture />` components by setting `image.experimentalLayout` with a default value. This can be overridden by the `layout` prop on each component.
*
Expand All @@ -2158,7 +2155,7 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
* {
* image: {
* // Used for all `<Image />` and `<Picture />` components unless overridden
* experimentalLayout: 'responsive',
* experimentalLayout: 'constrained',
* },
* experimental: {
* responsiveImages: true,
Expand All @@ -2183,12 +2180,12 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
*
* These are additional properties available to the `<Image />` and `<Picture />` components when responsive images are enabled:
*
* - `layout`: The layout type for the image. Can be `responsive`, `fixed`, `full-width` or `none`. Defaults to value of `image.experimentalLayout`.
* - `layout`: The layout type for the image. Can be `constrained`, `fixed`, `full-width` or `none`. Defaults to value of `image.experimentalLayout`.
* - `fit`: Defines how the image should be cropped if the aspect ratio is changed. Values match those of CSS `object-fit`. Defaults to `cover`, or the value of `image.experimentalObjectFit` if set.
* - `position`: Defines the position of the image crop if the aspect ratio is changed. Values match those of CSS `object-position`. Defaults to `center`, or the value of `image.experimentalObjectPosition` if set.
* - `priority`: If set, eagerly loads the image. Otherwise images will be lazy-loaded. Use this for your largest above-the-fold image. Defaults to `false`.
*
* The `widths` and `sizes` attributes are automatically generated based on the image's dimensions and the layout type, and in most cases should not be set manually. The generated `sizes` attribute for `responsive` and `full-width` images
* The `widths` and `sizes` attributes are automatically generated based on the image's dimensions and the layout type, and in most cases should not be set manually. The generated `sizes` attribute for `constrained` and `full-width` images
* is based on the assumption that the image is displayed at close to the full width of the screen when the viewport is smaller than the image's width. If it is significantly different (e.g. if it's in a multi-column layout on small screens) you may need to adjust the `sizes` attribute manually for best results.
*
* The `densities` attribute is not compatible with responsive images and will be ignored if set.
Expand Down
24 changes: 6 additions & 18 deletions packages/astro/test/core-image-layout.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,22 +86,16 @@ describe('astro:image:layout', () => {

it('sets the style', () => {
let $img = $('#local-both img');
assert.match($img.attr('style'), /--w: 300/);
assert.match($img.attr('style'), /--h: 400/);
assert.equal($img.data('astro-image'), 'responsive');
assert.equal($img.data('astro-image'), 'constrained');
});

it('sets the style when no dimensions set', () => {
let $img = $('#local img');
assert.match($img.attr('style'), /--w: 2316/);
assert.match($img.attr('style'), /--h: 1544/);
assert.equal($img.data('astro-image'), 'responsive');
assert.equal($img.data('astro-image'), 'constrained');
});

it('sets style for fixed image', () => {
let $img = $('#local-fixed img');
assert.match($img.attr('style'), /--w: 800/);
assert.match($img.attr('style'), /--h: 600/);
assert.equal($img.data('astro-image'), 'fixed');
});

Expand Down Expand Up @@ -396,8 +390,8 @@ describe('astro:image:layout', () => {
it('adds inline style attributes', () => {
let $img = $('#picture-attributes img');
const style = $img.attr('style');
assert.match(style, /--w:/);
assert.match(style, /--h:/);
assert.match(style, /--fit:/);
assert.match(style, /--pos:/);
});

it('passing in style as an object', () => {
Expand Down Expand Up @@ -645,22 +639,16 @@ describe('astro:image:layout', () => {

it('sets the style', () => {
let $img = $('#local-both img');
assert.match($img.attr('style'), /--w: 300/);
assert.match($img.attr('style'), /--h: 400/);
assert.equal($img.data('astro-image'), 'responsive');
assert.equal($img.data('astro-image'), 'constrained');
});

it('sets the style when no dimensions set', () => {
let $img = $('#local img');
assert.match($img.attr('style'), /--w: 2316/);
assert.match($img.attr('style'), /--h: 1544/);
assert.equal($img.data('astro-image'), 'responsive');
assert.equal($img.data('astro-image'), 'constrained');
});

it('sets style for fixed image', () => {
let $img = $('#local-fixed img');
assert.match($img.attr('style'), /--w: 800/);
assert.match($img.attr('style'), /--h: 600/);
assert.equal($img.data('astro-image'), 'fixed');
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { defineConfig } from 'astro/config';

export default defineConfig({
image: {
experimentalLayout: 'responsive',
experimentalLayout: 'constrained',
},

experimental: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@ import bigPenguin from "../assets/penguin.jpg";
</div>

<div id="responsive">
<Image src={bigPenguin} alt="Astro" layout="responsive" width="1000" />
<Image src={bigPenguin} alt="Astro" layout="constrained" width="1000" />
</div>