Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(AspectRatio): add fit prop for component-owned child sizing (#3882)

Jiun Shin26fb921527ae
diff --git a/.changeset/aspectratio-fit-prop.md b/.changeset/aspectratio-fit-prop.md
new file mode 100644
index 0000000000..3b862eb7f2
--- /dev/null
+++ b/.changeset/aspectratio-fit-prop.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] AspectRatio: add a `fit` prop (`'cover' | 'contain' | 'center'`) so the component sizes and positions its child instead of every consumer hand-writing `width`/`height`/`objectFit` on the child. `cover`/`contain` ship as zero-specificity baseline rules in `reset.css` keyed on a `data-astryx-aspect-ratio-override` marker the component sets on the child's direct parent (direct-child selectors, no dependence on internal structure or the theming surface), so a child's own styles always win and self-sized children are unchanged; `center` centers the child at its natural size from the component's wrapper. When `fit` is omitted the child is left unstyled, preserving the existing contract (#2753)
+@jiunshinn
diff --git a/apps/storybook/stories/AspectRatio.stories.tsx b/apps/storybook/stories/AspectRatio.stories.tsx
index 0a2f403bba..21c4b7d6b4 100644
--- a/apps/storybook/stories/AspectRatio.stories.tsx
+++ b/apps/storybook/stories/AspectRatio.stories.tsx
@@ -31,10 +31,9 @@ const styles = stylex.create({
sectionLabel: {
marginBlockEnd: spacingVars['--spacing-2'],
},
+ // Sizing comes from fit="cover" on AspectRatio; only the radius is
+ // story-specific.
image: {
- width: '100%',
- height: '100%',
- objectFit: 'cover',
borderRadius: radiusVars['--radius-element'],
},
placeholder: {
@@ -81,6 +80,12 @@ const meta: Meta<typeof AspectRatio> = {
description:
'Container shape. Both respect the ratio; "ellipse" clips to an oval (circle at 1:1).',
},
+ fit: {
+ control: 'select',
+ options: [undefined, 'cover', 'contain', 'center'],
+ description:
+ 'How the child is sized inside the ratio box; omitted leaves the child unstyled.',
+ },
},
};
@@ -94,6 +99,7 @@ const PLACEHOLDER_SQUARE = 'https://picsum.photos/400/400';
export const Default: Story = {
args: {
ratio: 16 / 9,
+ fit: 'cover',
},
render: args => (
<div {...stylex.props(styles.container)}>
@@ -117,7 +123,7 @@ export const Widescreen16x9: Story = {
<Text type="supporting" xstyle={styles.sectionLabel}>
16:9 - Standard widescreen (YouTube, TV)
</Text>
- <AspectRatio ratio={16 / 9}>
+ <AspectRatio ratio={16 / 9} fit="cover">
<img
{...stylex.props(styles.image)}
src={PLACEHOLDER_IMAGE}
@@ -134,7 +140,7 @@ export const Classic4x3: Story = {
<Text type="supporting" xstyle={styles.sectionLabel}>
4:3 - Classic TV and photography
</Text>
- <AspectRatio ratio={4 / 3}>
+ <AspectRatio ratio={4 / 3} fit="cover">
<img
{...stylex.props(styles.image)}
src={PLACEHOLDER_IMAGE}
@@ -151,7 +157,7 @@ export const Square1x1: Story = {
<Text type="supporting" xstyle={styles.sectionLabel}>
1:1 - Square (Instagram, avatars)
</Text>
- <AspectRatio ratio={1}>
+ <AspectRatio ratio={1} fit="cover">
<img
{...stylex.props(styles.image)}
src={PLACEHOLDER_SQUARE}
@@ -181,6 +187,7 @@ export const EllipseCircle: Story = {
args: {
ratio: 1,
shape: 'ellipse',
+ fit: 'cover',
},
render: args => (
<div {...stylex.props(styles.smallContainer)}>
@@ -202,6 +209,7 @@ export const EllipseOval: Story = {
args: {
ratio: 16 / 9,
shape: 'ellipse',
+ fit: 'cover',
},
render: args => (
<div {...stylex.props(styles.container)}>
@@ -219,6 +227,49 @@ export const EllipseOval: Story = {
),
};
+export const FitModes: Story = {
+ render: () => (
+ <div {...stylex.props(styles.storyWrapper)}>
+ <div {...stylex.props(styles.container)}>
+ <Text type="supporting" xstyle={styles.sectionLabel}>
+ fit="cover" — fills the box, media is cropped
+ </Text>
+ <AspectRatio ratio={16 / 9} fit="cover">
+ <img
+ {...stylex.props(styles.image)}
+ src={PLACEHOLDER_SQUARE}
+ alt="Cropped to fill"
+ />
+ </AspectRatio>
+ </div>
+ <div {...stylex.props(styles.container)}>
+ <Text type="supporting" xstyle={styles.sectionLabel}>
+ fit="contain" — fills the box, media is letterboxed
+ </Text>
+ <AspectRatio ratio={16 / 9} fit="contain">
+ <img
+ {...stylex.props(styles.image)}
+ src={PLACEHOLDER_SQUARE}
+ alt="Letterboxed to stay visible"
+ />
+ </AspectRatio>
+ </div>
+ <div {...stylex.props(styles.container)}>
+ <Text type="supporting" xstyle={styles.sectionLabel}>
+ fit="center" — natural size, centered
+ </Text>
+ <AspectRatio ratio={16 / 9} fit="center">
+ <img
+ {...stylex.props(styles.image)}
+ src="https://picsum.photos/200/120"
+ alt="Natural size, centered"
+ />
+ </AspectRatio>
+ </div>
+ </div>
+ ),
+};
+
export const WithPlaceholderSkeleton: Story = {
render: () => (
<div {...stylex.props(styles.storyWrapper)}>
@@ -335,7 +386,7 @@ export const ImageGallery: Story = {
</Text>
<Grid columns={3} gap={4}>
{Array.from({length: 6}, (_, i) => (
- <AspectRatio key={i} ratio={4 / 3}>
+ <AspectRatio key={i} ratio={4 / 3} fit="cover">
<img
{...stylex.props(styles.image)}
src={`https://picsum.photos/seed/${i + 1}/400/300`}
diff --git a/packages/cli/templates/blocks/components/AspectRatio/AspectRatioCircleImage.tsx b/packages/cli/templates/blocks/components/AspectRatio/AspectRatioCircleImage.tsx
index ffc79372cc..b41dbe8721 100644
--- a/packages/cli/templates/blocks/components/AspectRatio/AspectRatioCircleImage.tsx
+++ b/packages/cli/templates/blocks/components/AspectRatio/AspectRatioCircleImage.tsx
@@ -8,15 +8,10 @@ import {Center} from '@astryxdesign/core/Center';
export default function AspectRatioCircleImage() {
return (
<Center width={300}>
- <AspectRatio ratio={1} shape="ellipse">
+ <AspectRatio ratio={1} shape="ellipse" fit="cover">
<img
src="https://lookaside.facebook.com/assets/astryx/light-home-square-1.png"
alt="Circular image"
- style={{
- width: '100%',
- height: '100%',
- objectFit: 'cover',
- }}
/>
</AspectRatio>
</Center>
diff --git a/packages/cli/templates/blocks/components/AspectRatio/AspectRatioImageGallery.tsx b/packages/cli/templates/blocks/components/AspectRatio/AspectRatioImageGallery.tsx
index 4ca8da4b32..f94880e594 100644
--- a/packages/cli/templates/blocks/components/AspectRatio/AspectRatioImageGallery.tsx
+++ b/packages/cli/templates/blocks/components/AspectRatio/AspectRatioImageGallery.tsx
@@ -25,16 +25,11 @@ export default function AspectRatioImageGallery() {
<Center width={600}>
<Grid columns={3} gap={4} width="100%">
{images.map(({id, alt}) => (
- <AspectRatio key={id} ratio={4 / 3}>
+ <AspectRatio key={id} ratio={4 / 3} fit="cover">
<img
src="https://lookaside.facebook.com/assets/astryx/illustrative-horizontal-1.png"
alt={alt}
- style={{
- width: '100%',
- height: '100%',
- objectFit: 'cover',
- borderRadius: 8,
- }}
+ style={{borderRadius: 8}}
/>
</AspectRatio>
))}
diff --git a/packages/cli/templates/blocks/components/AspectRatio/AspectRatioShowcase.tsx b/packages/cli/templates/blocks/components/AspectRatio/AspectRatioShowcase.tsx
index a018e6e037..a5ec90026e 100644
--- a/packages/cli/templates/blocks/components/AspectRatio/AspectRatioShowcase.tsx
+++ b/packages/cli/templates/blocks/components/AspectRatio/AspectRatioShowcase.tsx
@@ -34,16 +34,13 @@ export default function AspectRatioShowcase() {
<VStack key={label} gap={2} hAlign="center">
<AspectRatio
ratio={ratio}
+ fit="cover"
style={{
height: 120,
width: 'auto',
borderRadius: 'var(--radius-container)',
}}>
- <img
- src={src}
- alt={alt}
- style={{width: '100%', height: '100%', objectFit: 'cover'}}
- />
+ <img src={src} alt={alt} />
</AspectRatio>
<Text type="supporting" color="secondary">
{label}
diff --git a/packages/cli/templates/blocks/components/AspectRatio/AspectRatioSquareImage.tsx b/packages/cli/templates/blocks/components/AspectRatio/AspectRatioSquareImage.tsx
index e76659816b..b2565a766b 100644
--- a/packages/cli/templates/blocks/components/AspectRatio/AspectRatioSquareImage.tsx
+++ b/packages/cli/templates/blocks/components/AspectRatio/AspectRatioSquareImage.tsx
@@ -8,15 +8,10 @@ import {Center} from '@astryxdesign/core/Center';
export default function AspectRatioSquareImage() {
return (
<Center width={300}>
- <AspectRatio ratio={1}>
+ <AspectRatio ratio={1} fit="cover">
<img
src="https://lookaside.facebook.com/assets/astryx/light-home-square-1.png"
alt="1:1 square"
- style={{
- width: '100%',
- height: '100%',
- objectFit: 'cover',
- }}
/>
</AspectRatio>
</Center>
diff --git a/packages/cli/templates/blocks/components/AspectRatio/AspectRatioWidescreen.tsx b/packages/cli/templates/blocks/components/AspectRatio/AspectRatioWidescreen.tsx
index 9096518975..4bd288fca1 100644
--- a/packages/cli/templates/blocks/components/AspectRatio/AspectRatioWidescreen.tsx
+++ b/packages/cli/templates/blocks/components/AspectRatio/AspectRatioWidescreen.tsx
@@ -8,15 +8,10 @@ import {Center} from '@astryxdesign/core/Center';
export default function AspectRatioWidescreen() {
return (
<Center width={600}>
- <AspectRatio ratio={16 / 9}>
+ <AspectRatio ratio={16 / 9} fit="cover">
<img
src="https://lookaside.facebook.com/assets/astryx/light-scene-horizontal-1.png"
alt="16:9 widescreen"
- style={{
- width: '100%',
- height: '100%',
- objectFit: 'cover',
- }}
/>
</AspectRatio>
</Center>
diff --git a/packages/core/src/AspectRatio/AspectRatio.doc.mjs b/packages/core/src/AspectRatio/AspectRatio.doc.mjs
index be46f465f2..5f540c4a65 100644
--- a/packages/core/src/AspectRatio/AspectRatio.doc.mjs
+++ b/packages/core/src/AspectRatio/AspectRatio.doc.mjs
@@ -13,6 +13,7 @@ export const docs = {
bestPractices: [
{guidance: true, description: 'Express the ratio as a fraction like `16/9` or `4/3` for readability.'},
{guidance: true, description: 'Use for media that needs consistent proportions across screen sizes.'},
+ {guidance: true, description: 'Use `fit="cover"` for images and video so the component sizes the child; the child should not repeat `width`/`height`/`objectFit` styles.'},
{guidance: false, description: 'Use for general layout containers; use standard layout components instead.'},
{guidance: false, description: 'Nest AspectRatio containers; one level is sufficient.'},
],
@@ -24,6 +25,17 @@ export const docs = {
description: 'Aspect ratio as width/height (e.g. 16/9, 1).',
required: true,
},
+ {
+ name: 'shape',
+ type: "'rectangle' | 'ellipse'",
+ description: 'Container shape. Both respect the `ratio`. `ellipse` clips to an oval (a circle when `ratio={1}`).',
+ default: "'rectangle'",
+ },
+ {
+ name: 'fit',
+ type: "'cover' | 'contain' | 'center'",
+ description: 'How the child is sized inside the ratio box. `cover` fills and crops media, `contain` fills and letterboxes, `center` keeps the natural size centered. When omitted, the child styles itself.',
+ },
{
name: 'children',
type: 'ReactNode',
@@ -60,12 +72,24 @@ export const docsZh = {
bestPractices: [
{guidance: true, description: 'Express the ratio as a fraction like `16/9` or `4/3` for readability.'},
{guidance: true, description: 'Use for media that needs consistent proportions across screen sizes.'},
+ {guidance: true, description: 'Use `fit="cover"` for images and video so the component sizes the child; the child should not repeat `width`/`height`/`objectFit` styles.'},
{guidance: false, description: 'Use for general layout containers; use standard layout components instead.'},
{guidance: false, description: 'Nest AspectRatio containers; one level is sufficient.'},
],
},
props: [
{name: 'ratio', type: 'number', description: '宽高比,以宽/高表示(例如 16/9、1)。', required: true},
+ {
+ name: 'shape',
+ type: "'rectangle' | 'ellipse'",
+ description: '容器形状。两种形状都遵循 `ratio`。`ellipse` 裁剪为椭圆(`ratio={1}` 时为正圆)。',
+ default: "'rectangle'",
+ },
+ {
+ name: 'fit',
+ type: "'cover' | 'contain' | 'center'",
+ description: '子元素在比例框内的布局方式。`cover` 填满并裁剪媒体,`contain` 填满并留边,`center` 保持原始尺寸居中。省略时子元素自行设置样式。',
+ },
{name: 'children', type: 'ReactNode', description: '通过绝对定位填充容器的内容。', required: true},
{
name: 'xstyle',
@@ -76,7 +100,7 @@ export const docsZh = {
],
theming: {
targets: [
- {className: 'astryx-aspect-ratio'},
+ {className: 'astryx-aspect-ratio', visualProps: ['shape']},
],
},
};
@@ -90,12 +114,15 @@ export const docsDense = {
bestPractices: [
{guidance: true, description: 'Express the ratio as a fraction like `16/9` or `4/3` for readability.'},
{guidance: true, description: 'Use for media that needs consistent proportions across screen sizes.'},
+ {guidance: true, description: 'Use `fit="cover"` for images and video so the component sizes the child; the child should not repeat `width`/`height`/`objectFit` styles.'},
{guidance: false, description: 'Use for general layout containers; use standard layout components instead.'},
{guidance: false, description: 'Nest AspectRatio containers; one level is sufficient.'},
],
},
propDescriptions: {
ratio: 'width/height ratio (e.g. 16/9, 1)',
+ shape: "container shape: 'rectangle' (default) | 'ellipse' (circle at ratio 1)",
+ fit: "child layout: 'cover' fill+crop | 'contain' fill+letterbox | 'center' natural size; omitted = child styles itself",
children: 'content positioned absolutely to fill container',
xstyle: 'StyleX layout customization via stylex.create()',
},
diff --git a/packages/core/src/AspectRatio/AspectRatio.test.tsx b/packages/core/src/AspectRatio/AspectRatio.test.tsx
index 88b8ccb796..9605fb63a5 100644
--- a/packages/core/src/AspectRatio/AspectRatio.test.tsx
+++ b/packages/core/src/AspectRatio/AspectRatio.test.tsx
@@ -9,7 +9,7 @@
* SYNC: When AspectRatio.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi} from 'vitest';
+import {describe, it, expect, vi, beforeAll} from 'vitest';
import {render, screen} from '@testing-library/react';
import {AspectRatio} from './AspectRatio';
@@ -176,4 +176,145 @@ describe('AspectRatio', () => {
const video = screen.getByTestId('video');
expect(video).toBeInTheDocument();
});
+
+ describe('fit', () => {
+ it('marks the child\'s direct parent with data-astryx-aspect-ratio-override for fit="cover"', () => {
+ render(
+ <AspectRatio ratio={16 / 9} fit="cover">
+ <img src="test.jpg" alt="Test" data-testid="image" />
+ </AspectRatio>,
+ );
+ // The marker sits on the child's actual parent, so the reset.css
+ // sizing rules are direct-child selectors with no dependence on
+ // AspectRatio's internal structure.
+ const wrapper = screen.getByTestId('image').parentElement;
+ expect(wrapper).toHaveAttribute(
+ 'data-astryx-aspect-ratio-override',
+ 'cover',
+ );
+ });
+
+ it('marks the child\'s direct parent with data-astryx-aspect-ratio-override for fit="contain"', () => {
+ render(
+ <AspectRatio ratio={16 / 9} fit="contain">
+ <img src="test.jpg" alt="Test" data-testid="image" />
+ </AspectRatio>,
+ );
+ const wrapper = screen.getByTestId('image').parentElement;
+ expect(wrapper).toHaveAttribute(
+ 'data-astryx-aspect-ratio-override',
+ 'contain',
+ );
+ });
+
+ it('does not expose fit on the theming surface', () => {
+ render(
+ <AspectRatio ratio={16 / 9} fit="cover" data-testid="aspect-ratio">
+ <img src="test.jpg" alt="Test" />
+ </AspectRatio>,
+ );
+ const element = screen.getByTestId('aspect-ratio');
+ // fit is structural, not visual — no data-fit attribute or class
+ // token on the themeable root (only shape is a theming target).
+ expect(element).not.toHaveAttribute('data-fit');
+ expect(element.className).not.toContain('cover');
+ });
+
+ it('emits no marker when fit is omitted (back-compat)', () => {
+ render(
+ <AspectRatio ratio={16 / 9} data-testid="aspect-ratio">
+ <img src="test.jpg" alt="Test" data-testid="image" />
+ </AspectRatio>,
+ );
+ const wrapper = screen.getByTestId('image').parentElement;
+ expect(wrapper).not.toHaveAttribute('data-astryx-aspect-ratio-override');
+ // Without the marker, none of the reset.css fit rules can match, so
+ // existing self-styled children render exactly as before.
+ expect(screen.getByTestId('image')).not.toHaveAttribute('class');
+ });
+
+ it('never touches the child element props', () => {
+ render(
+ <AspectRatio ratio={16 / 9} fit="cover">
+ <img
+ src="test.jpg"
+ alt="Test"
+ data-testid="image"
+ className="consumer-class"
+ style={{objectFit: 'contain'}}
+ />
+ </AspectRatio>,
+ );
+ const image = screen.getByTestId('image');
+ // Fit styling is pure CSS (zero-specificity reset rules); the child's
+ // own className/style pass through untouched and always win, so
+ // children that already size themselves keep their behavior.
+ expect(image.className).toBe('consumer-class');
+ expect(image.style.objectFit).toBe('contain');
+ });
+
+ it('centers the child via the wrapper with fit="center"', () => {
+ render(
+ <AspectRatio ratio={16 / 9} fit="center">
+ <img src="test.jpg" alt="Test" data-testid="image" />
+ </AspectRatio>,
+ );
+ const image = screen.getByTestId('image');
+ expect(image).not.toHaveAttribute('class');
+ const wrapper = image.parentElement;
+ expect(wrapper?.className).toContain('childCenter');
+ });
+
+ it('does not center the wrapper for other fit values', () => {
+ render(
+ <AspectRatio ratio={16 / 9} fit="cover">
+ <img src="test.jpg" alt="Test" data-testid="image" />
+ </AspectRatio>,
+ );
+ const wrapper = screen.getByTestId('image').parentElement;
+ expect(wrapper?.className).not.toContain('childCenter');
+ });
+ });
+
+ describe('reset.css fit baseline rules', () => {
+ // The cover/contain child sizing ships as zero-specificity baseline
+ // rules in reset.css keyed on the data-astryx-aspect-ratio-override
+ // marker the component sets on the child's direct parent. These
+ // assertions keep the stylesheet in sync with the component contract.
+ let resetCSS: string;
+
+ beforeAll(async () => {
+ const fs = await import('fs');
+ const path = await import('path');
+ resetCSS = fs.readFileSync(
+ path.resolve(__dirname, '../reset.css'),
+ 'utf-8',
+ );
+ });
+
+ it('sizes the child to fill the box for cover and contain', () => {
+ const fillMatch = resetCSS.match(
+ /:where\(\[data-astryx-aspect-ratio-override="cover"\], \[data-astryx-aspect-ratio-override="contain"\]\)\s*>\s*:where\(\*\)\s*\{([^}]+)\}/,
+ );
+ expect(fillMatch).not.toBeNull();
+ expect(fillMatch![1]).toContain('width: 100%');
+ expect(fillMatch![1]).toContain('height: 100%');
+ });
+
+ it('crops media with object-fit: cover for fit="cover"', () => {
+ const coverMatch = resetCSS.match(
+ /:where\(\[data-astryx-aspect-ratio-override="cover"\]\)\s*>\s*:where\(img, video\)\s*\{([^}]+)\}/,
+ );
+ expect(coverMatch).not.toBeNull();
+ expect(coverMatch![1]).toContain('object-fit: cover');
+ });
+
+ it('letterboxes media with object-fit: contain for fit="contain"', () => {
+ const containMatch = resetCSS.match(
+ /:where\(\[data-astryx-aspect-ratio-override="contain"\]\)\s*>\s*:where\(img, video\)\s*\{([^}]+)\}/,
+ );
+ expect(containMatch).not.toBeNull();
+ expect(containMatch![1]).toContain('object-fit: contain');
+ });
+ });
});
diff --git a/packages/core/src/AspectRatio/AspectRatio.tsx b/packages/core/src/AspectRatio/AspectRatio.tsx
index 37673d299e..afb036bbf9 100644
--- a/packages/core/src/AspectRatio/AspectRatio.tsx
+++ b/packages/core/src/AspectRatio/AspectRatio.tsx
@@ -5,12 +5,13 @@
/**
* @file AspectRatio.tsx
* @input Uses React, stylex
- * @output Exports AspectRatio component and AspectRatioProps
+ * @output Exports AspectRatio component, AspectRatioProps, AspectRatioShape, AspectRatioFit
* @position AspectRatio component; maintains a specific aspect ratio for its children
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/AspectRatio/AspectRatio.doc.mjs
* - /packages/core/src/AspectRatio/AspectRatio.test.tsx
+ * - /packages/core/src/reset.css (AspectRatio fit baseline rules)
* - /apps/storybook/stories/AspectRatio.stories.tsx
* - /packages/cli/templates/blocks/components/AspectRatio/ (showcase blocks)
*/
@@ -29,6 +30,16 @@ import {themeProps} from '../utils/themeProps';
*/
export type AspectRatioShape = 'rectangle' | 'ellipse';
+/**
+ * How the child is sized and positioned inside the ratio box.
+ * - `cover`: the child fills the box; media is cropped to preserve its own
+ * aspect ratio (`object-fit: cover`).
+ * - `contain`: the child fills the box; media is letterboxed to stay fully
+ * visible (`object-fit: contain`).
+ * - `center`: the child keeps its natural size and sits centered in the box.
+ */
+export type AspectRatioFit = 'cover' | 'contain' | 'center';
+
export interface AspectRatioProps extends BaseProps<HTMLDivElement> {
/** Ref forwarded to the root element */
ref?: React.Ref<HTMLDivElement>;
@@ -41,20 +52,45 @@ export interface AspectRatioProps extends BaseProps<HTMLDivElement> {
* The shape of the container. Both shapes respect the provided `ratio`.
* - `rectangle` (default): a standard rectangular container.
* - `ellipse`: clips the container to an ellipse — a circle when `ratio={1}`,
- * or an oval at other ratios. Pair with a child that fills the container
- * (e.g. an image with `objectFit: 'cover'`).
+ * or an oval at other ratios. Pair with `fit="cover"` so the media fills
+ * the clipped container.
*
* @default 'rectangle'
*
* @example
* ```
- * <AspectRatio ratio={1} shape="ellipse">
- * <img src="avatar.jpg" alt="" style={{objectFit: 'cover'}} />
+ * <AspectRatio ratio={1} shape="ellipse" fit="cover">
+ * <img src="avatar.jpg" alt="" />
* </AspectRatio>
* ```
*/
shape?: AspectRatioShape;
+ /**
+ * How the child is laid out inside the ratio box, so the child does not
+ * have to declare `width`/`height`/`objectFit` itself.
+ * - `cover`: child fills the box; media is cropped (`object-fit: cover`).
+ * - `contain`: child fills the box; media is letterboxed
+ * (`object-fit: contain`).
+ * - `center`: child keeps its natural size, centered in the box.
+ *
+ * `cover`/`contain` child sizing ships as zero-specificity baseline rules
+ * in `reset.css`, keyed on the `data-astryx-aspect-ratio-override`
+ * attribute the component sets on the child's direct parent. Any styles
+ * the child sets itself still win, so children that already size
+ * themselves keep their behavior. When omitted, the child is left
+ * unstyled (the pre-existing contract). `fit` is structural, not visual,
+ * so it is not exposed on the theming surface.
+ *
+ * @example
+ * ```
+ * <AspectRatio ratio={16 / 9} fit="cover">
+ * <img src="image.jpg" alt="Widescreen image" />
+ * </AspectRatio>
+ * ```
+ */
+ fit?: AspectRatioFit;
+
/**
* Content to render inside the aspect ratio container.
* The child element will be positioned absolutely to fill the container.
@@ -82,6 +118,16 @@ const styles = stylex.create({
width: '100%',
height: '100%',
},
+ // fit="center" centers the child at its natural size from the wrapper —
+ // no styles on the child itself. The `cover`/`contain` child sizing can't
+ // live here (StyleX has no descendant selectors); it ships as baseline
+ // rules in reset.css keyed on the `data-astryx-aspect-ratio-override`
+ // attribute the wrapper carries (see below).
+ childCenter: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
});
/**
@@ -91,27 +137,32 @@ const styles = stylex.create({
* is positioned absolutely to fill the container, which is useful for images,
* videos, embeds, and placeholders.
*
+ * Use `fit` to let the component size the child: `cover`/`contain` stretch
+ * the child to fill the box (cropping or letterboxing media), `center` keeps
+ * the child at its natural size. Without `fit`, the child styles itself.
+ *
* Use `shape="ellipse"` to clip the container into an ellipse — a circle at
* `ratio={1}` or an oval at other ratios. Both shapes respect the provided
* `ratio`.
*
* @example
* ```
- * <AspectRatio ratio={16 / 9}>
- * <img src="image.jpg" alt="Widescreen image" style={{objectFit: 'cover'}} />
+ * <AspectRatio ratio={16 / 9} fit="cover">
+ * <img src="image.jpg" alt="Widescreen image" />
* </AspectRatio>
* ```
*
* @example
* ```
- * <AspectRatio ratio={1} shape="ellipse">
- * <img src="avatar.jpg" alt="" style={{objectFit: 'cover'}} />
+ * <AspectRatio ratio={1} shape="ellipse" fit="cover">
+ * <img src="avatar.jpg" alt="" />
* </AspectRatio>
* ```
*/
export function AspectRatio({
ratio,
shape = 'rectangle',
+ fit,
children,
xstyle,
className,
@@ -133,7 +184,16 @@ export function AspectRatio({
{...style, aspectRatio: ratio},
)}
{...props}>
- <div {...stylex.props(styles.child)}>{children}</div>
+ {/* The marker attribute carries the fit value so the reset.css child
+ sizing can use direct-child selectors on this wrapper — the child's
+ actual parent — without depending on AspectRatio's internal
+ structure or on the theming surface (fit is structural, not
+ themeable). The name is namespaced to avoid collisions. */}
+ <div
+ data-astryx-aspect-ratio-override={fit}
+ {...stylex.props(styles.child, fit === 'center' && styles.childCenter)}>
+ {children}
+ </div>
</div>
);
}
diff --git a/packages/core/src/AspectRatio/index.ts b/packages/core/src/AspectRatio/index.ts
index 4efaa124d7..589575466a 100644
--- a/packages/core/src/AspectRatio/index.ts
+++ b/packages/core/src/AspectRatio/index.ts
@@ -12,4 +12,8 @@
*/
export {AspectRatio} from './AspectRatio';
-export type {AspectRatioProps, AspectRatioShape} from './AspectRatio';
+export type {
+ AspectRatioProps,
+ AspectRatioShape,
+ AspectRatioFit,
+} from './AspectRatio';
diff --git a/packages/core/src/reset.css b/packages/core/src/reset.css
index 8dde7f9558..f8941ed48e 100644
--- a/packages/core/src/reset.css
+++ b/packages/core/src/reset.css
@@ -200,6 +200,35 @@
height: auto;
}
+ /* ===========================================================================
+ AspectRatio Fit Baseline
+ =========================================================================== */
+
+ /*
+ * Child sizing for AspectRatio's `fit` prop — the component marks the
+ * child's direct parent with `data-astryx-aspect-ratio-override` (carrying
+ * the fit value), and these direct-child rules size the child, so
+ * consumers don't hand-write width/height/object-fit on every media child.
+ * The marker sits on the parent itself, so the rules don't depend on
+ * AspectRatio's internal element structure or its theming surface. As with
+ * the [data-astryx-media] baseline below, the rules are zero-specificity
+ * and any styling the child sets itself still wins. `fit="center"` needs
+ * no rules here — the component centers the child from its own wrapper.
+ */
+ :where([data-astryx-aspect-ratio-override="cover"], [data-astryx-aspect-ratio-override="contain"])
+ > :where(*) {
+ width: 100%;
+ height: 100%;
+ }
+
+ :where([data-astryx-aspect-ratio-override="cover"]) > :where(img, video) {
+ object-fit: cover;
+ }
+
+ :where([data-astryx-aspect-ratio-override="contain"]) > :where(img, video) {
+ object-fit: contain;
+ }
+
/* ===========================================================================
Forms
=========================================================================== */