Skip to content

Aspect ratio

Keeps content at a width-to-height ratio.

View as Markdown

Example

Installation

npx fizzy-ui add aspect-ratio

Copies aspect-ratio.ts into src/app/ui/ and installs what it needs. Run init once first.

Accessibility

No axe-core violations axe-core 4.14.0 checks this example, closed and with its panels open, on every build; the site is not published otherwise.

  • Only layout: CSS aspect-ratio, nothing for assistive technology to read.
  • An image inside still needs its alt text.

Source

The exact file add copies. It is yours to edit.

aspect-ratio.ts
import { Directive, input } from '@angular/core';

/**
 * Keeps its content at a ratio as the width changes: `<div fzAspectRatio="16 / 9"><img …></div>`.
 * The ratio is CSS `aspect-ratio` (a number or "w / h"); an image or video inside fills it, cropped.
 */
@Directive({
  selector: '[fzAspectRatio]',
  host: {
    '[style.aspect-ratio]': 'ratio()',
    class: 'relative block w-full overflow-hidden [&>*]:size-full [&>img]:object-cover [&>video]:object-cover',
  },
})
export class FzAspectRatio {
  readonly ratio = input<number | string>(1, { alias: 'fzAspectRatio' });
}

export const FZ_ASPECT_RATIO = [FzAspectRatio] as const;