Aspect Ratio
Displays content within a desired ratio.
import * as stylex from '@stylexjs/stylex';
import { AspectRatio } from '@/components/ui/aspect-ratio';
import { container } from '@/lib/constants.stylex';
import { radius } from '@/lib/tokens.stylex';
export default function AspectRatioDemo() {
return (
<div {...stylex.props(styles.frame)}>
<AspectRatio ratio={16 / 9}>
<img
src="https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=800&dpr=2&q=80"
alt="Landscape by Drew Beamer"
{...stylex.props(styles.image)}
/>
</AspectRatio>
</div>
);
}
const styles = stylex.create({
frame: {
width: container.lg,
},
image: {
borderRadius: radius.lg,
height: '100%',
objectFit: 'cover',
width: '100%',
},
});
Install
npx shadcn@latest add @madeui/aspect-ratio
Usage
import { AspectRatio } from '@/components/ui/aspect-ratio';
Square
import * as stylex from '@stylexjs/stylex';
import { AspectRatio } from '@/components/ui/aspect-ratio';
import { container } from '@/lib/constants.stylex';
import { colors, radius } from '@/lib/tokens.stylex';
export default function AspectRatioSquare() {
return (
<div {...stylex.props(styles.frame)}>
<AspectRatio ratio={1 / 1}>
<div {...stylex.props(styles.placeholder)} />
</AspectRatio>
</div>
);
}
const styles = stylex.create({
frame: {
width: container.xs,
},
placeholder: {
backgroundColor: colors.muted,
borderRadius: radius.lg,
height: '100%',
width: '100%',
},
});
Portrait
import * as stylex from '@stylexjs/stylex';
import { AspectRatio } from '@/components/ui/aspect-ratio';
import { container } from '@/lib/constants.stylex';
import { colors, radius } from '@/lib/tokens.stylex';
export default function AspectRatioPortrait() {
return (
<div {...stylex.props(styles.frame)}>
<AspectRatio ratio={9 / 16}>
<div {...stylex.props(styles.placeholder)} />
</AspectRatio>
</div>
);
}
const styles = stylex.create({
frame: {
width: container.xs,
},
placeholder: {
backgroundColor: colors.muted,
borderRadius: radius.lg,
height: '100%',
width: '100%',
},
});
API reference
A plain <div> using the CSS aspect-ratio property.
| Prop | Type | Default | Description |
|---|---|---|---|
ratio |
number |
— | Width / height, e.g. 16 / 9. |
style |
StyleXStyles |
— | StyleX styles merged last — always win over the component’s own styles. |