Componentaspect-ratio
Aspect Ratio
Displays content within a desired ratio.
Preview
Displays content within a desired ratio.
16 : 9
@ui.AspectRatio(ui.AspectRatioProps{Ratio: 16.0 / 9.0, DOMProps: ui.DOMProps{Class: "bg-muted rounded-md overflow-hidden"}}) {
<img src="https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=800&dpr=2&q=80" alt="Photo by Drew Beamer" class="h-full w-full object-cover"/>
}Installation
Add this component to your project using the CLI.
templcn add aspect-ratioUsage
1. Import the component in your Go or templ file:
import "your-module/ui"2. Use the component in your template:
@ui.AspectRatio(ui.AspectRatioProps{Ratio: 16.0 / 9.0, DOMProps: ui.DOMProps{Class: "bg-muted rounded-md overflow-hidden"}}) {
<img src="https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=800&dpr=2&q=80" alt="Photo by Drew Beamer" class="h-full w-full object-cover"/>
}Composition
Use these parts together to build the component.
AspectRatioExamples
Named examples and common variations.
16:9
A 16:9 aspect ratio container.
16 : 9
@ui.AspectRatio(ui.AspectRatioProps{Ratio: 16.0/9.0, DOMProps: ui.DOMProps{Class: "w-full max-w-xs rounded-md overflow-hidden bg-muted"}}) {
<div class="flex h-full items-center justify-center text-sm">16 : 9</div>
}API Reference
| Prop | Type | Default | Description |
|---|---|---|---|
| Ratio | float64 | 1 | The width-to-height ratio (e.g. 16.0/9.0). |
View source
package ui
import (
"context"
"fmt"
"io"
"strconv"
"github.com/a-h/templ"
)
type AspectRatioProps struct {
DOMProps
Ratio float64
}
func AspectRatio(props AspectRatioProps) templ.Component {
return templ.ComponentFunc(func(ctx context.Context, w io.Writer) error {
ratio := props.Ratio
if ratio <= 0 {
ratio = 1
}
attrs := attrsFromDOMProps(props.DOMProps, "aspect-ratio", "relative w-full overflow-hidden")
style := fmt.Sprintf("aspect-ratio: %s;", strconv.FormatFloat(ratio, 'f', -1, 64))
if existing, ok := attrs["style"]; ok {
style = cn(templ.Classes(existing).String(), style)
}
attrs["style"] = style
return renderElement(ctx, w, "div", attrs, templ.GetChildren(ctx))
})
}