Skip to content
Gx
GitHub

Aspect Ratio

A box that keeps a fixed width to height ratio.

<aspectratio.AspectRatio ratio="16 / 9" class="rounded-lg bg-muted">16 / 9</aspectratio.AspectRatio>

Installation

Run the command in the app module.

Terminal
gx add aspect-ratio

The command writes these files.

File Path in the app
AspectRatio.gx ui/aspect-ratio/AspectRatio.gx
AspectRatio.fixtures.go ui/aspect-ratio/AspectRatio.fixtures.go
styles.go ui/aspect-ratio/styles.go

Copy each file to its path in the app. Change each import of a registry package to the path of that package in the app.

ui/aspect-ratio/AspectRatio.gx
package aspectratio

props {
  // Ratio is the CSS aspect-ratio value, width over height, for example 4 / 3. An empty value is
  // 16 / 9.
  Ratio    string = "16 / 9"
  // Class adds classes to the root element.
  Class    string = ""
  // Children is the content of the box, for example an image.
  Children gx.Node
  // Attrs adds HTML attributes to the root element.
  Attrs    gx.Attrs = nil
}

<div data-slot="aspect-ratio" style={gx.Style("aspect-ratio: " + p.ratio())} class={gx.Cx("relative w-full overflow-hidden", p.Class)} {...p.Attrs}>{p.Children}</div>
ui/aspect-ratio/AspectRatio.fixtures.go
package aspectratio

import "github.com/alternayte/gx"

var AspectRatioFixtures = gx.Fixtures[AspectRatioProps]{
	"Wide":   {Ratio: "16 / 9", Class: "rounded-lg bg-muted", Children: gx.Text("16 / 9")},
	"Square": {Ratio: "1 / 1", Class: "max-w-40 rounded-lg bg-muted", Children: gx.Text("1 / 1")},
}
ui/aspect-ratio/styles.go
package aspectratio

// ratio returns the CSS ratio; a zero value is 16 / 9.
func (p AspectRatioProps) ratio() string {
	if p.Ratio == "" {
		return "16 / 9"
	}
	return p.Ratio
}

Usage

<aspectratio.AspectRatio ratio="16 / 9" class="rounded-lg bg-muted">
  <img src={gx.URL("/hero.jpg")} alt="Hero" class="size-full object-cover" />
</aspectratio.AspectRatio>

Examples

Wide

<aspectratio.AspectRatio ratio="16 / 9" class="rounded-lg bg-muted">16 / 9</aspectratio.AspectRatio>

Square

<aspectratio.AspectRatio ratio="1 / 1" class="max-w-40 rounded-lg bg-muted">1 / 1</aspectratio.AspectRatio>

API reference

A tag sets a prop by its name with a lower-case first letter: Class is class.

aspectratio.AspectRatio

Prop Type Default Description
Ratio string "16 / 9" Ratio is the CSS aspect-ratio value, width over height, for example 4 / 3. An empty value is 16 / 9.
Class string "" Class adds classes to the root element.
Children gx.Node Required Children is the content of the box, for example an image.
Attrs gx.Attrs nil Attrs adds HTML attributes to the root element.

Do and do not

Do

  • Set Ratio as a CSS ratio, for example 16 / 9.
  • Let the child fill the box with size-full.

Don't

  • Do not use an aspect ratio for text content.
  • Do not nest aspect ratio boxes.

Keyboard

Key Action
None The component is static.