Aspect ratio
Keeps media at a fixed width-to-height ratio, cropping images to fill.
Installation
bash
npx bootcn add aspect-ratiobash
pnpm dlx bootcn add aspect-ratiobash
yarn dlx bootcn add aspect-ratiobash
bunx --bun bootcn add aspect-ratioThe CLI also installs the design tokens and these components: none. It prints the <link> and <script> tags to add to your layout.
Usage
Set the ratio with --bootcn-aspect-ratio (for example 1 / 1 or 4 / 3). Images and videos inside are cropped to fill (object-fit: cover). For embeds you can also use Bootstrap's .ratio classes.
Accessibility
- Give images a meaningful
alt, oralt=""when they are decorative. - Embedded iframes need a
title.
Dependencies
- Bootstrap 5.3+ CSS.
themes/tokens/tokens.css.
Source
The exact files the CLI installs (aspect-ratio@1.0.0). View on GitHub · Report an issue
html
<div class="bootcn-aspect-ratio" style="--bootcn-aspect-ratio: 16 / 9; max-width: 32rem">
<img
src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 360'%3E%3Cdefs%3E%3ClinearGradient id='s' x1='0' y1='0' x2='0' y2='1'%3E%3Cstop offset='0' stop-color='%23fde68a'/%3E%3Cstop offset='1' stop-color='%23fb7185'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='640' height='360' fill='url(%23s)'/%3E%3Ccircle cx='470' cy='130' r='46' fill='%23fff7ed'/%3E%3Cpath d='M0 260 160 150 270 230 380 140 640 280V360H0z' fill='%239f1239'/%3E%3Cpath d='M0 300 200 220 330 290 460 230 640 310V360H0z' fill='%234c0519'/%3E%3C/svg%3E"
alt="Illustration of hills at sunset"
/>
</div>css
.bootcn-aspect-ratio {
--bootcn-aspect-ratio: 16 / 9;
position: relative;
width: 100%;
overflow: hidden;
border-radius: var(--bootcn-radius-lg);
background-color: var(--bootcn-muted);
aspect-ratio: var(--bootcn-aspect-ratio);
}
.bootcn-aspect-ratio > img,
.bootcn-aspect-ratio > video,
.bootcn-aspect-ratio > iframe {
width: 100%;
height: 100%;
border: 0;
object-fit: cover;
}
