x-bind Directive

Dynamically bind HTML attributes – classes, styles, src, href, aria-* and more.

What is x-bind?

x-bind allows you to dynamically set any HTML attribute based on Alpine data. The shorthand is :attribute. This is one of the most versatile directives, working for classes, styles, images, links, and even ARIA attributes.

💡 Tip

Use :class for conditional classes – it’s the most common binding. You can pass an object or an array of classes.

When to Use

Use x-bind whenever an attribute value depends on component state – dynamic CSS classes, disabled states, custom data attributes, or even SVG properties. It keeps your template clean without inline JavaScript string concatenation.

Basic Syntax

Code
<div x-data="{ isActive: false, buttonText: 'Click me' }">
  <button
    :class="isActive ? 'bg-blue-500' : 'bg-gray-300'"
    :disabled="!isActive"
    @click="isActive = !isActive"
    x-text="buttonText"
  ></button>
</div>

Binding Objects

For classes, you can bind an object where keys are class names and values are booleans. This is cleaner than ternary operators for multiple classes.

Code
<div :class="{ 'text-red-500': hasError, 'font-bold': isImportant }"></div>

Common Patterns

  • :src="imageUrl" – dynamic images.
  • :href="'/users/' + userId" – dynamic links.
  • :style="{ color: activeColor }" – inline styles.
  • :aria-expanded="open" – accessibility attributes.
Can I bind multiple attributes at once?

You bind them one by one, but you can also use x-bind with a key-value object (via Alpine.bind()) to reuse a set of attributes across different elements.

⚠️ Warning

Be careful when binding user‑provided data to style or innerHTML – it can lead to XSS vulnerabilities. Always sanitize the data.

Helpful? Share this page!↑ Back to top