Skip to content
Esc
↑↓navigate↵open⌘Jpreview
On this page

Astro Hexagon Pattern

A hexagon background that fills its container. The hover effect is optional.

Hover effect

Hexagon pattern

Installation

bunx --bun shadcn@latest add @gnostic/hexagon-pattern
npx shadcn@latest add @gnostic/hexagon-pattern
pnpm dlx shadcn@latest add @gnostic/hexagon-pattern

Complete the Installation guide first. Then copy the component files below.

No extra packages are required.

Copy the files

src/components/patterns/hexagon-pattern/hexagon-pattern.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"
import { mergeStyles } from "../../../lib/merge-styles.ts"

import { hexagonMetrics } from "./hexagon-pattern.ts"
import type { HexagonPatternProps } from "./types.ts"

/**
 * Hexagon background.
 *
 * The field fills this element. A script counts the rows from the box size.
 * `hoverEffect` adds the hover color classes. Those classes are the whole effect.
 */
type Props = HTMLAttributes<"div"> & HexagonPatternProps

const {
  hexagonSize = 75,
  hexagonMargin = 3,
  hoverEffect = false,
  hexagonColor = "var(--background)",
  gapColor,
  hoverFill = "var(--muted)",
  hoverStroke = "color-mix(in oklch, var(--foreground) 18%, var(--background))",
  hexagonClass,
  class: className,
  style: styleProp,
  ...props
} = Astro.props

const metrics = hexagonMetrics(hexagonSize, hexagonMargin)

/**
 * Hover classes. The docs switch reads this string and adds or removes it.
 * Keep the names here so the switch and `hoverEffect` stay the same.
 */
const hexagonHoverClasses =
  "hover:before:bg-[var(--hexagon-hover-stroke)] hover:before:duration-0 hover:after:bg-[var(--hexagon-hover-fill)] hover:after:duration-0"

/** Point-top hexagon. The inner layer uses the same shape. */
const hexagonClip =
  "[clip-path:polygon(50%_0%,_100%_25%,_100%_75%,_50%_100%,_0%_75%,_0%_25%)]"
const hexagonInnerClip =
  "after:[clip-path:polygon(50%_0%,_100%_25%,_100%_75%,_50%_100%,_0%_75%,_0%_25%)]"

const style = mergeStyles(
  {
    "--hexagon-margin": `${hexagonMargin}px`,
    "--hexagon-width": `${metrics.hexagonWidth}px`,
    "--hexagon-height": `${metrics.hexagonHeight}px`,
    "--hexagon-fill": hexagonColor,
    "--hexagon-stroke": hexagonColor,
    "--hexagon-hover-fill": hoverFill,
    "--hexagon-hover-stroke": hoverStroke,
    ...(gapColor ? { "background-color": gapColor } : {}),
  },
  styleProp,
)
---

<div
  data-slot="hexagon-pattern"
  data-hover-effect={hoverEffect ? "true" : "false"}
  data-hover-class={hexagonHoverClasses}
  data-hexagon-width={metrics.hexagonWidth}
  data-row-spacing={metrics.rowSpacing}
  data-row-margin-top={metrics.marginTop}
  data-odd-row-margin-left={metrics.oddRowMarginLeft}
  data-even-row-margin-left={metrics.evenRowMarginLeft}
  class={cn(
    "relative isolate h-full w-full overflow-hidden bg-muted",
    className,
  )}
  style={style}
  {...props}
>
  <div
    aria-hidden="true"
    data-hexagon-grid
    class="absolute inset-0 -z-10 overflow-hidden"
  ></div>
  {/*
    One cell. The script clones it into the grid.
    The hover classes are on this cell only when `hoverEffect` is true.
  */}
  <template data-hexagon-template>
    <div
      data-slot="hexagon"
      class={cn(
        "relative shrink-0",
        hexagonClip,
        "before:absolute before:inset-0 before:bg-[var(--hexagon-stroke)] before:transition-colors before:duration-1000 before:content-[''] motion-reduce:before:transition-none",
        "after:absolute after:inset-[var(--hexagon-margin)] after:bg-[var(--hexagon-fill)] after:content-['']",
        hexagonInnerClip,
        hoverEffect && hexagonHoverClasses,
        hexagonClass,
      )}
      style="width: var(--hexagon-width); height: var(--hexagon-height); margin-left: var(--hexagon-margin)"
    ></div>
  </template>
  <slot />
</div>

<script>
  import {
    createHexagonPattern,
    type HexagonPatternController,
  } from "./hexagon-pattern.ts"

  const controllers: HexagonPatternController[] = []

  /** Drop observers before a new page view or a repeat init. */
  function cleanup() {
    for (const controller of controllers) controller.destroy()
    controllers.length = 0
  }

  /** Measure every hexagon pattern currently in the document. */
  function init() {
    cleanup()
    document
      .querySelectorAll<HTMLElement>('[data-slot="hexagon-pattern"]')
      .forEach((root) => {
        controllers.push(createHexagonPattern(root))
      })
  }

  init()
  document.addEventListener("astro:page-load", init)
  document.addEventListener("astro:before-swap", cleanup)
</script>
src/components/patterns/hexagon-pattern/hexagon-pattern.ts
/** Sizes the script needs to fill the box with hexagon rows. */
export type HexagonMetrics = {
    /** Cell width, in pixels. This matches `hexagonSize`. */
    hexagonWidth: number
    /** Cell height, in pixels. */
    hexagonHeight: number
    /** Distance from one row's top to the next row's top, in pixels. */
    rowSpacing: number
    /** Negative top margin that pulls each row up by the overlap, in pixels. */
    marginTop: number
    /** Left offset for a row that starts on a hexagon point, in pixels. */
    oddRowMarginLeft: number
    /** Left offset for a row that starts between two hexagons, in pixels. */
    evenRowMarginLeft: number
}

export type HexagonPatternController = {
    /** Stop watching this pattern. Call this before the node leaves the page. */
    destroy: () => void
}

/** Pull every row left so the clipped edge has no empty strip. */
const ROW_BLEED = 10

const active = new WeakMap<HTMLElement, () => void>()

/**
 * Measure one hexagon tile.
 *
 * Rows overlap on the slanted edge. The margin term keeps that edge the
 * same thickness as the straight gap, so every border is `hexagonMargin`.
 *
 * @param hexagonSize - Hexagon width, in pixels.
 * @param hexagonMargin - Gap and border thickness, in pixels.
 * @returns Row and cell offsets for the grid script.
 */
export function hexagonMetrics(
    hexagonSize: number,
    hexagonMargin: number,
): HexagonMetrics {
    const hexagonWidth = hexagonSize
    const hexagonHeight = hexagonSize * 1.1
    const corner = hexagonHeight / 4
    const side = Math.hypot(corner, hexagonWidth / 2)
    const rowSpacing =
        hexagonHeight -
        corner +
        (hexagonMargin * (2 * side - corner)) / hexagonWidth

    return {
        hexagonWidth,
        hexagonHeight,
        rowSpacing,
        marginTop: rowSpacing - hexagonHeight,
        oddRowMarginLeft: -(hexagonSize / 2),
        evenRowMarginLeft: hexagonMargin / 2,
    }
}

/**
 * Fill one pattern with hexagon rows and keep the count matched to the box.
 *
 * The template holds one cell. This function clones that cell, so a change
 * to the template class is copied the next time the grid is built.
 * A second call for the same root replaces the earlier observer.
 *
 * @param root - Element with `data-slot="hexagon-pattern"`.
 * @returns Teardown for the resize observer.
 */
export function createHexagonPattern(
    root: HTMLElement,
): HexagonPatternController {
    active.get(root)?.()

    const grid = root.querySelector<HTMLElement>('[data-hexagon-grid]')
    const template = root.querySelector<HTMLTemplateElement>(
        'template[data-hexagon-template]',
    )
    const width = Number(root.dataset.hexagonWidth)
    const rowSpacing = Number(root.dataset.rowSpacing)
    const marginTop = Number(root.dataset.rowMarginTop)
    const oddLeft = Number(root.dataset.oddRowMarginLeft)
    const evenLeft = Number(root.dataset.evenRowMarginLeft)

    let rows = -1
    let columns = -1
    let observer: ResizeObserver | undefined

    /** Rebuild the rows when the box size needs a different cell count. */
    const paint = () => {
        const cell = template?.content.querySelector<HTMLElement>(
            '[data-slot="hexagon"]',
        )
        if (!grid || !cell) return
        if (
            !Number.isFinite(width) ||
            width <= 0 ||
            !Number.isFinite(rowSpacing) ||
            rowSpacing <= 0
        )
            return

        const box = root.getBoundingClientRect()
        // A hidden box has no size yet. Wait for the next observation.
        if (box.width === 0 || box.height === 0) return

        const nextRows = Math.ceil(box.height / rowSpacing) + 1
        const nextColumns = Math.ceil(box.width / width) + 1
        if (nextRows === rows && nextColumns === columns) return
        rows = nextRows
        columns = nextColumns

        const fragment = document.createDocumentFragment()
        for (let rowIndex = 0; rowIndex < rows; rowIndex++) {
            const row = document.createElement('div')
            row.className = 'flex w-max'
            row.style.marginTop = `${marginTop}px`
            const even = (rowIndex + 1) % 2 === 0
            row.style.marginLeft = `${(even ? evenLeft : oddLeft) - ROW_BLEED}px`
            for (let column = 0; column < columns; column++)
                row.append(cell.cloneNode(true))
            fragment.append(row)
        }
        grid.replaceChildren(fragment)
    }

    paint()
    if (typeof ResizeObserver !== 'undefined') {
        observer = new ResizeObserver(paint)
        observer.observe(root)
    }

    const destroy = () => {
        observer?.disconnect()
        rows = -1
        columns = -1
        active.delete(root)
    }
    active.set(root, destroy)
    return { destroy }
}
src/components/patterns/hexagon-pattern/index.ts
export { default as HexagonPattern } from './hexagon-pattern.astro'
export type { HexagonPatternProps } from './types.ts'
src/components/patterns/hexagon-pattern/types.ts
/**
 * Hexagon field that fills its box.
 *
 * The component draws one cell for each tile. `hoverEffect` adds the
 * hover color classes. The gap color is the component background.
 */
export type HexagonPatternProps = {
    /**
     * Width of one hexagon, in pixels.
     * The height is 1.1 times this width.
     *
     * @default 75
     */
    hexagonSize?: number
    /**
     * Space between hexagons, in pixels.
     * This space is also the border thickness.
     *
     * @default 3
     */
    hexagonMargin?: number
    /**
     * Change each hexagon color when the pointer is over it.
     *
     * @default false
     */
    hoverEffect?: boolean
    /**
     * CSS color of each hexagon.
     *
     * @default "var(--background)"
     */
    hexagonColor?: string
    /**
     * CSS color of the space between hexagons.
     * Leave this unset to use the `bg-muted` class.
     * A caller `bg-*` class can replace that class.
     */
    gapColor?: string
    /**
     * CSS color of the hexagon fill while the pointer is over it.
     * Used when `hoverEffect` is true.
     *
     * @default "var(--muted)"
     */
    hoverFill?: string
    /**
     * CSS color of the hexagon border while the pointer is over it.
     * Used when `hoverEffect` is true.
     *
     * @default "color-mix(in oklch, var(--foreground) 18%, var(--background))"
     */
    hoverStroke?: string
    /**
     * Extra classes for each hexagon.
     * Use this to replace a fill or a hover color.
     */
    hexagonClass?: string
}

Usage

The component is the box. Give it a height. The script fills that box with hexagon rows. Content in the slot sits above the field. Give text relative z-10 when the text must stay above the hexagons.

import { HexagonPattern } from "@/components/patterns/hexagon-pattern"
<HexagonPattern class="h-72" />

hoverEffect adds the hover color classes. Leave it unset for a static field.

<HexagonPattern hoverEffect class="h-72" />

hexagonSize is the width of one hexagon, in pixels. hexagonMargin is the gap. That gap is also the border thickness. hexagonColor paints each hexagon. gapColor paints the space between them. Leave gapColor unset to use bg-muted.

hoverFill and hoverStroke are the colors used while the pointer is over a hexagon. They apply only when hoverEffect is true.

Each preview has a Hover effect switch. The switch adds or removes the same classes as hoverEffect.

Examples

Large hexagons

hexagonSize sets the width. A larger size uses fewer cells.

Hover effect

Large hexagons

Small hexagons

A smaller size uses more cells. Lower hexagonMargin to keep the gap thin.

Hover effect

Small hexagons

Gradient overlay

A gradient layer covers part of the field. pointer-events-none lets the pointer reach the hexagons that remain visible.

Hover effect

Part of the field stays visible

Custom colors

gapColor, hexagonColor, hoverFill, and hoverStroke accept any CSS color. The two fields below use different sets of those colors.

Hover effect

Primary

Contrast

Without the hover effect

Leave hoverEffect unset. The switch at the top can still turn the classes on.

Hover effect

No hover effect

API Reference

HexagonPatternProps

PropType
hexagonSize?number

Width of one hexagon, in pixels. The height is 1.1 times this width.

Typenumber
Default75
hexagonMargin?number

Space between hexagons, in pixels. This space is also the border thickness.

Typenumber
Default3
hoverEffect?boolean

Change each hexagon color when the pointer is over it.

Typeboolean
Defaultfalse
hexagonColor?string

CSS color of each hexagon.

Typestring
Default"var(--background)"
gapColor?string

CSS color of the space between hexagons. Leave this unset to use the `bg-muted` class. A caller `bg-*` class can replace that class.

Typestring
hoverFill?string

CSS color of the hexagon fill while the pointer is over it. Used when `hoverEffect` is true.

Typestring
Default"var(--muted)"
hoverStroke?string

CSS color of the hexagon border while the pointer is over it. Used when `hoverEffect` is true.

Typestring
Default"color-mix(in oklch, var(--foreground) 18%, var(--background))"
hexagonClass?string

Extra classes for each hexagon. Use this to replace a fill or a hover color.

Typestring

See the registry source for the component source.