backgrounds

Background utilities for Tailwind CSS

Background Attachment

Control how a background image behaves when scrolling:


BackgroundAttachment


def BackgroundAttachment(
    args:VAR_POSITIONAL, kwds:VAR_KEYWORD
):

Background attachment utility values

Exported source
class BackgroundAttachment(Enum):
    """Background attachment utility values"""
    FIXED = "fixed"
    LOCAL = "local"
    SCROLL = "scroll"

bg_attachment = enums_to_simple_factory("bg", [BackgroundAttachment], "Background attachment utilities for controlling how a background image behaves when scrolling") # Background attachment factory

test_backgrounds_attachment_examples


def test_backgrounds_attachment_examples(
    
):

Test background attachment utilities.

Exported source
def test_backgrounds_attachment_examples():
    """Test background attachment utilities."""
    assert str(bg_attachment.fixed) == "bg-fixed"
    assert str(bg_attachment.local) == "bg-local"
    assert str(bg_attachment.scroll) == "bg-scroll"

# Run the tests
test_backgrounds_attachment_examples()

Background Clip

Control the bounding box of an element’s background:


BackgroundClip


def BackgroundClip(
    args:VAR_POSITIONAL, kwds:VAR_KEYWORD
):

Background clip utility values

Exported source
class BackgroundClip(Enum):
    """Background clip utility values"""
    BORDER = "border"
    PADDING = "padding"
    CONTENT = "content"
    TEXT = "text"

bg_clip = enums_to_simple_factory("bg-clip", [BackgroundClip], "Background clip utilities for controlling the bounding box of an element's background") # Background clip factory

test_backgrounds_clip_examples


def test_backgrounds_clip_examples(
    
):

Test background clip utilities.

Exported source
def test_backgrounds_clip_examples():
    """Test background clip utilities."""
    assert str(bg_clip.border) == "bg-clip-border"
    assert str(bg_clip.padding) == "bg-clip-padding"
    assert str(bg_clip.content) == "bg-clip-content"
    assert str(bg_clip.text) == "bg-clip-text"

# Run the tests
test_backgrounds_clip_examples()

Background Color

The most commonly used background utility - sets the background color of an element:

Exported source
bg = ColoredFactory("bg", "Background color utilities for controlling an element's background color") # The background color factory

Basic Background Colors

Apply background colors using the standard color palette:


test_backgrounds_color_examples


def test_backgrounds_color_examples(
    
):

Test background color utilities with various color values.

Exported source
def test_backgrounds_color_examples():
    """Test background color utilities with various color values."""
    # Test all 22 Tailwind color families
    assert str(bg.red._500) == "bg-red-500"
    assert str(bg.orange._500) == "bg-orange-500"
    assert str(bg.amber._500) == "bg-amber-500"
    assert str(bg.yellow._500) == "bg-yellow-500"
    assert str(bg.lime._500) == "bg-lime-500"
    assert str(bg.green._500) == "bg-green-500"
    assert str(bg.emerald._500) == "bg-emerald-500"
    assert str(bg.teal._500) == "bg-teal-500"
    assert str(bg.cyan._500) == "bg-cyan-500"
    assert str(bg.sky._500) == "bg-sky-500"
    assert str(bg.blue._500) == "bg-blue-500"
    assert str(bg.indigo._500) == "bg-indigo-500"
    assert str(bg.violet._500) == "bg-violet-500"
    assert str(bg.purple._500) == "bg-purple-500"
    assert str(bg.fuchsia._500) == "bg-fuchsia-500"
    assert str(bg.pink._500) == "bg-pink-500"
    assert str(bg.rose._500) == "bg-rose-500"
    assert str(bg.slate._500) == "bg-slate-500"
    assert str(bg.gray._500) == "bg-gray-500"
    assert str(bg.zinc._500) == "bg-zinc-500"
    assert str(bg.neutral._500) == "bg-neutral-500"
    assert str(bg.stone._500) == "bg-stone-500"
    
    # Test different shades
    assert str(bg.blue._300) == "bg-blue-300"
    assert str(bg.green._950) == "bg-green-950"
    
    # Special colors
    assert str(bg.transparent) == "bg-transparent"
    assert str(bg.black) == "bg-black"
    assert str(bg.white) == "bg-white"
    assert str(bg.current) == "bg-current"
    assert str(bg.inherit) == "bg-inherit"

# Run the tests
test_backgrounds_color_examples()

Background Opacity

Control the opacity of background colors:


test_backgrounds_opacity_examples


def test_backgrounds_opacity_examples(
    
):

Test background colors with opacity modifiers.

Exported source
def test_backgrounds_opacity_examples():
    """Test background colors with opacity modifiers."""
    # Standard opacity values
    assert str(bg.red._500.opacity(50)) == "bg-red-500/50"
    assert str(bg.blue._300.opacity(75)) == "bg-blue-300/75"
    assert str(bg.black.opacity(10)) == "bg-black/10"
    
    # Arbitrary opacity values
    assert str(bg.green._600.opacity("[0.87]")) == "bg-green-600/[0.87]"
    assert str(bg.purple._400.opacity("(--my-opacity)")) == "bg-purple-400/(--my-opacity)"

# Run the tests
test_backgrounds_opacity_examples()

Background Image

Control an element’s background image:

No Background Image

Remove background images:

Exported source
bg_none = SingleValueFactory("bg-none", "Remove background image") # Remove background image

Linear Gradients

Create linear gradient backgrounds:


GradientUtility


def GradientUtility(
    gradient_type:str, # Type of gradient (linear, radial, conic)
    value:Union=None, # Direction, angle, or custom value
    negative:bool=False, # Whether to negate the angle
):

Utility class for gradient backgrounds with angle support.

Gradient Backgrounds

Create gradient backgrounds with various types:


GradientFactory


def GradientFactory(
    gradient_type:str, # Type of gradient (linear, radial, conic)
    doc:Optional=None, # Documentation
):

Factory for gradient utilities with angle and direction support.

Exported source
# Create gradient factories
bg_linear = GradientFactory("linear", "Linear gradient utilities for creating gradient backgrounds")
bg_radial = GradientFactory("radial", "Radial gradient utilities for creating circular gradient backgrounds") 
bg_conic = GradientFactory("conic", "Conic gradient utilities for creating conical gradient backgrounds")

Gradient Color Stops

Define color stops for gradients:


GradientStopUtility


def GradientStopUtility(
    stop_type:str, # Type of stop (from, via, to)
    value:Union=None, # Color or percentage
    is_position:bool=False, # Whether this is a position value
):

Utility class for gradient color stops with percentage support.


GradientStopFactory


def GradientStopFactory(
    stop_type:str, # Type of stop (from, via, to)
    doc:Optional=None, # Documentation
):

Enhanced factory for gradient color stops with percentage support.

Exported source
# Create enhanced gradient stop factories
from_color = GradientStopFactory("from", "Gradient from color/position utilities for defining the starting color or position of a gradient")
via_color = GradientStopFactory("via", "Gradient via color/position utilities for defining the middle color or position of a gradient")
to_color = GradientStopFactory("to", "Gradient to color/position utilities for defining the ending color or position of a gradient")

Test Background Image Utilities


test_backgrounds_gradient_examples


def test_backgrounds_gradient_examples(
    
):

Test gradient background utilities.

Exported source
def test_backgrounds_gradient_examples():
    """Test gradient background utilities."""
    # Test bg-none
    assert str(bg_none) == "bg-none"
    
    # Test linear gradient directions
    assert str(bg_linear.to_t) == "bg-linear-to-t"
    assert str(bg_linear.to_tr) == "bg-linear-to-tr"
    assert str(bg_linear.to_r) == "bg-linear-to-r"
    assert str(bg_linear.to_br) == "bg-linear-to-br"
    assert str(bg_linear.to_b) == "bg-linear-to-b"
    assert str(bg_linear.to_bl) == "bg-linear-to-bl"
    assert str(bg_linear.to_l) == "bg-linear-to-l"
    assert str(bg_linear.to_tl) == "bg-linear-to-tl"
    
    # Test linear gradient angles
    assert str(bg_linear._45) == "bg-linear-45"
    assert str(bg_linear._90) == "bg-linear-90"
    assert str(bg_linear._180) == "bg-linear-180"
    assert str(bg_linear(45)) == "bg-linear-45"
    assert str(bg_linear(90, negative=True)) == "-bg-linear-90"
    assert str(bg_linear.neg_45) == "-bg-linear-45"
    
    # Test radial gradient
    assert str(bg_radial()) == "bg-radial"
    assert str(bg_radial("--gradient-shape")) == "bg-radial-(--gradient-shape)"
    assert str(bg_radial("circle at center")) == "bg-radial-[circle at center]"
    
    # Test conic gradient
    assert str(bg_conic._45) == "bg-conic-45"
    assert str(bg_conic(90)) == "bg-conic-90"
    assert str(bg_conic(180, negative=True)) == "-bg-conic-180"
    assert str(bg_conic("--conic-angle")) == "bg-conic-(--conic-angle)"
    assert str(bg_conic("from 45deg at center")) == "bg-conic-[from 45deg at center]"

# Run the tests
test_backgrounds_gradient_examples()

test_backgrounds_gradient_stops_examples


def test_backgrounds_gradient_stops_examples(
    
):

Test gradient color stop utilities.

Exported source
def test_backgrounds_gradient_stops_examples():
    """Test gradient color stop utilities."""
    # Test from colors
    assert str(from_color.red._500) == "from-red-500"
    assert str(from_color.blue._300) == "from-blue-300"
    assert str(from_color.transparent) == "from-transparent"
    assert str(from_color.black.opacity(50)) == "from-black/50"
    
    # Test from percentages
    assert str(from_color._0) == "from-0%"
    assert str(from_color._50) == "from-50%"
    assert str(from_color._100) == "from-100%"
    assert str(from_color(25)) == "from-25%"
    assert str(from_color("33%")) == "from-33%"
    
    # Test from custom properties and arbitrary values
    assert str(from_color("--gradient-start")) == "from-(--gradient-start)"
    assert str(from_color("10px")) == "from-[10px]"
    
    # Test via colors
    assert str(via_color.green._400) == "via-green-400"
    assert str(via_color.purple._600) == "via-purple-600"
    assert str(via_color.white) == "via-white"
    assert str(via_color.yellow._200.opacity(75)) == "via-yellow-200/75"
    
    # Test via percentages
    assert str(via_color._50) == "via-50%"
    assert str(via_color(75)) == "via-75%"
    
    # Test to colors
    assert str(to_color.pink._500) == "to-pink-500"
    assert str(to_color.indigo._700) == "to-indigo-700"
    assert str(to_color.current) == "to-current"
    assert str(to_color.cyan._300.opacity(25)) == "to-cyan-300/25"
    
    # Test to percentages
    assert str(to_color._100) == "to-100%"
    assert str(to_color(90)) == "to-90%"
    assert str(to_color("--gradient-end")) == "to-(--gradient-end)"

# Run the tests
test_backgrounds_gradient_stops_examples()

Gradient Examples

Practical examples of creating gradients:


test_backgrounds_gradient_composition_examples


def test_backgrounds_gradient_composition_examples(
    
):

Test composing gradient backgrounds with color stops.

Exported source
def test_backgrounds_gradient_composition_examples():
    """Test composing gradient backgrounds with color stops."""
    from fasthtml.common import Div
    from cjm_fasthtml_tailwind.utilities.spacing import p
    from cjm_fasthtml_tailwind.utilities.typography import font_size, text_color
    
    # Simple two-color gradient
    gradient1 = Div(
        "Gradient Background",
        cls=combine_classes(
            bg_linear.to_r,
            from_color.blue._500,
            to_color.purple._600,
            p(8),
            text_color.white
        )
    )
    assert "bg-linear-to-r" in gradient1.attrs['class']
    assert "from-blue-500" in gradient1.attrs['class']
    assert "to-purple-600" in gradient1.attrs['class']
    
    # Three-color gradient with via
    gradient2 = Div(
        "Three Color Gradient",
        cls=combine_classes(
            bg_linear.to_br,
            from_color.red._400,
            via_color.yellow._500,
            to_color.green._600,
            p(8),
            text_color.white
        )
    )
    assert "via-yellow-500" in gradient2.attrs['class']
    
    # Gradient with angle
    gradient3 = Div(
        "Angled Gradient",
        cls=combine_classes(
            bg_linear._45,
            from_color.indigo._500,
            to_color.pink._500,
            p(8)
        )
    )
    assert "bg-linear-45" in gradient3.attrs['class']
    
    # Radial gradient
    radial = Div(
        "Radial Gradient",
        cls=combine_classes(
            bg_radial(),
            from_color.indigo._300,
            to_color.pink._500,
            p(16)
        )
    )
    assert "bg-radial" in radial.attrs['class']
    
    # Conic gradient
    conic = Div(
        "Conic Gradient",
        cls=combine_classes(
            bg_conic._180,
            from_color.red._500,
            via_color.yellow._500,
            to_color.blue._500,
            p(16)
        )
    )
    assert "bg-conic-180" in conic.attrs['class']
    
    # Gradient with opacity
    gradient_opacity = Div(
        "Semi-transparent gradient",
        cls=combine_classes(
            bg_linear.to_t,
            from_color.black.opacity(90),
            to_color.transparent,
            p(8)
        )
    )
    assert "from-black/90" in gradient_opacity.attrs['class']
    assert "to-transparent" in gradient_opacity.attrs['class']
    
    # Gradient with position percentages
    gradient_positions = Div(
        "Gradient with positions",
        cls=combine_classes(
            bg_linear.to_r,
            from_color.blue._500,
            from_color._10,  # Start at 10%
            via_color.green._500,
            via_color._50,   # Middle at 50%
            to_color.red._500,
            to_color._90,    # End at 90%
            p(8)
        )
    )
    assert "from-10%" in gradient_positions.attrs['class']
    assert "via-50%" in gradient_positions.attrs['class']
    assert "to-90%" in gradient_positions.attrs['class']

# Run the tests
test_backgrounds_gradient_composition_examples()

Background Origin

Control how an element’s background is positioned relative to borders, padding, and content:


test_backgrounds_origin_examples


def test_backgrounds_origin_examples(
    
):

Test background origin utilities.

Exported source
bg_origin = SimpleFactory(
    {
        "border": "bg-origin-border",
        "padding": "bg-origin-padding",
        "content": "bg-origin-content"
    },
    "Background origin utilities for controlling how an element's background is positioned relative to borders, padding, and content"
) # Background origin factory
Exported source
def test_backgrounds_origin_examples():
    """Test background origin utilities."""
    assert str(bg_origin.border) == "bg-origin-border"
    assert str(bg_origin.padding) == "bg-origin-padding"
    assert str(bg_origin.content) == "bg-origin-content"

# Run the tests
test_backgrounds_origin_examples()

Background Position

Control the position of background images:


test_backgrounds_position_examples


def test_backgrounds_position_examples(
    
):

Test background position utilities.

Exported source
bg_position = SimpleFactory(
    {
        "top_left": "bg-top-left",
        "top": "bg-top",
        "top_right": "bg-top-right",
        "left": "bg-left",
        "center": "bg-center",
        "right": "bg-right",
        "bottom_left": "bg-bottom-left",
        "bottom": "bg-bottom",
        "bottom_right": "bg-bottom-right"
    },
    "Background position utilities for controlling the position of an element's background image"
) # Background position factory
Exported source
def test_backgrounds_position_examples():
    """Test background position utilities."""
    assert str(bg_position.top_left) == "bg-top-left"
    assert str(bg_position.top) == "bg-top"
    assert str(bg_position.top_right) == "bg-top-right"
    assert str(bg_position.center) == "bg-center"
    assert str(bg_position.bottom) == "bg-bottom"

# Run the tests
test_backgrounds_position_examples()

Background Repeat

Control the repetition of background images:


test_backgrounds_repeat_examples


def test_backgrounds_repeat_examples(
    
):

Test background repeat utilities.

Exported source
bg_repeat = SimpleFactory(
    {
        "repeat": "bg-repeat",
        "repeat_x": "bg-repeat-x",
        "repeat_y": "bg-repeat-y",
        "repeat_space": "bg-repeat-space",
        "repeat_round": "bg-repeat-round",
        "no_repeat": "bg-no-repeat"
    },
    "Background repeat utilities for controlling the repetition of an element's background image"
) # Background repeat factory
Exported source
def test_backgrounds_repeat_examples():
    """Test background repeat utilities."""
    assert str(bg_repeat.repeat) == "bg-repeat"
    assert str(bg_repeat.repeat_x) == "bg-repeat-x"
    assert str(bg_repeat.repeat_y) == "bg-repeat-y"
    assert str(bg_repeat.no_repeat) == "bg-no-repeat"

# Run the tests
test_backgrounds_repeat_examples()

Background Size

Control the background size of an element’s background image:


test_backgrounds_size_examples


def test_backgrounds_size_examples(
    
):

Test background size utilities.

Exported source
bg_size = SimpleFactory(
    {
        "auto": "bg-auto",
        "cover": "bg-cover",
        "contain": "bg-contain"
    },
    "Background size utilities for controlling the background size of an element's background image"
) # Background size factory
Exported source
def test_backgrounds_size_examples():
    """Test background size utilities."""
    assert str(bg_size.auto) == "bg-auto"
    assert str(bg_size.cover) == "bg-cover"
    assert str(bg_size.contain) == "bg-contain"

# Run the tests
test_backgrounds_size_examples()

Arbitrary Background Values

Test support for arbitrary background values:


test_backgrounds_arbitrary_examples


def test_backgrounds_arbitrary_examples(
    
):

Test background utilities with arbitrary values.

Exported source
def test_backgrounds_arbitrary_examples():
    """Test background utilities with arbitrary values."""
    # Arbitrary color values
    assert str(bg("#123456")) == "bg-[#123456]"
    assert str(bg("rgb(10, 20, 30)")) == "bg-[rgb(10, 20, 30)]"
    assert str(bg("linear-gradient(to right, red, blue)")) == "bg-[linear-gradient(to right, red, blue)]"
    
    # CSS custom properties
    assert str(bg("--custom-bg-color")) == "bg-(--custom-bg-color)"
    assert str(bg("--theme-background")) == "bg-(--theme-background)"

# Run the tests
test_backgrounds_arbitrary_examples()

Practical Examples

Let’s see how to use these background utilities in real FastHTML components:


test_backgrounds_fasthtml_examples


def test_backgrounds_fasthtml_examples(
    
):

Test background utilities in practical FastHTML component examples.

Exported source
def test_backgrounds_fasthtml_examples():
    """Test background utilities in practical FastHTML component examples."""
    from fasthtml.common import Div, H1, P, Section
    from cjm_fasthtml_tailwind.utilities.spacing import p
    from cjm_fasthtml_tailwind.utilities.borders import rounded
    from cjm_fasthtml_tailwind.utilities.typography import font_size, text_color
    from cjm_fasthtml_tailwind.utilities.layout import position
    from cjm_fasthtml_tailwind.utilities.flexbox_and_grid import gap, grid_display
    
    # Card with colored background
    card = Div(
        H1("Welcome", cls=str(text_color.white)),
        P("This is a card with a blue background"),
        cls=combine_classes(bg.blue._500, p(6), rounded.lg)
    )
    assert "bg-blue-500" in card.attrs['class']
    
    # Hero section with gradient overlay
    hero = Section(
        Div(
            H1("Hero Title"),
            cls=combine_classes(bg.black.opacity(50), p(8))
        ),
        cls=combine_classes(
            bg_size.cover,
            bg_position.center,
            bg_repeat.no_repeat,
            position.relative
        )
    )
    assert str(bg.black.opacity(50)) == "bg-black/50"
    assert "bg-cover" in hero.attrs['class']
    assert "bg-center" in hero.attrs['class']
    
    # Text with gradient background using v4 syntax
    gradient_text = H1(
        "Gradient Text",
        cls=combine_classes(
            bg_clip.text,
            text_color.transparent,
            bg_linear.to_r,
            from_color.blue._500,
            to_color.red._600,
            font_size._7xl
        )
    )
    assert "bg-clip-text" in gradient_text.attrs['class']
    assert "bg-linear-to-r" in gradient_text.attrs['class']
    assert "from-blue-500" in gradient_text.attrs['class']
    assert "to-red-600" in gradient_text.attrs['class']
    
    # Return all examples in a grid layout
    return Div(
        card,
        hero,
        gradient_text,
        cls=combine_classes(grid_display, gap(5))
    )

# Run the tests
test_backgrounds_fasthtml_examples()

Welcome

This is a card with a blue background

Hero Title

Gradient Text

test_func = test_backgrounds_fasthtml_examples
app, rt = create_test_app()

@rt
def index():
    return create_test_page(test_func.__doc__.title().replace('.', ''), test_func())
server = start_test_server(app)
display(HTMX())
server.stop()