Styling components
Master the art of dynamic styling in Aurelia 2. Learn everything from basic class toggling to advanced CSS custom properties, plus component styling strategies that will make your apps both beautiful
Dynamic styling is a fundamental aspect of modern web applications, and Aurelia 2 provides powerful, flexible mechanisms for binding CSS classes and styles to your elements. Whether you need to toggle an active state, implement a theming system, or create responsive layouts, Aurelia's binding system makes these tasks straightforward and maintainable.
This comprehensive guide covers everything from basic class toggling to advanced styling techniques, giving you the knowledge and tools to implement any styling requirement in your Aurelia 2 applications.
Basic Class Binding
The most common use case for dynamic styling is conditionally applying CSS classes based on component state.
Single Class Binding: The .class Syntax
.class SyntaxThe .class binding is the foundation of dynamic styling in Aurelia. The syntax is straightforward:
<button submit.class="isFormValid">Submit Form</button>
<div loading.class="isLoading">Content here...</div>
<nav-item active.class="isCurrentPage">Home</nav-item>export class MyComponent {
isFormValid = false;
isLoading = true;
isCurrentPage = false;
// When isFormValid becomes true, the 'submit' class gets added
// When isLoading is false, the 'loading' class gets removed
}How it works: The syntax is className.class="booleanExpression". When the expression is truthy, the class is added. When it's falsy, the class is removed.
TailwindCSS note: Tailwind’s content scanner won’t pick up class names that only appear in attribute names. For Tailwind classes that include special characters (for example width-[360px]), prefer the object form with class.bind so the class token appears in an attribute value:
Multiple Classes: Comma-Separated Syntax
When you need to toggle multiple related classes together, you can use comma-separated class names:
Important: No spaces around the commas! The parser expects class1,class2,class3, not class1, class2, class3.
Style Binding
Aurelia provides multiple approaches for binding CSS styles, from individual properties to complex style objects.
Single Style Properties
To bind individual CSS properties dynamically, use the .style syntax:
Alternative Style Syntax
Aurelia supports two equivalent syntaxes for style binding:
Use whichever feels more natural to you. Some developers prefer the first syntax because it reads like "set the background-color style to myColor", while others prefer the second because it's more similar to traditional CSS.
CSS Custom Properties
Aurelia fully supports CSS custom properties (CSS variables), enabling powerful theming capabilities:
Vendor Prefixes
Aurelia supports vendor-prefixed CSS properties for cross-browser compatibility:
The !important Declaration
!important DeclarationAurelia automatically handles the !important CSS declaration when included in style values:
Advanced Class Binding Techniques
Advanced class binding techniques provide greater flexibility for complex styling scenarios.
String-Based Class Binding
For scenarios requiring more flexibility than boolean toggling, you can bind class strings directly:
When to use what:
.classsyntax: When you need boolean toggling of specific classesclass.bind: When you need to build class strings dynamicallyTemplate interpolation: When you want to mix static and dynamic classes
Advanced Style Binding
Advanced style binding techniques enable sophisticated styling patterns and better code organization.
Object-Based Style Binding
For complex styling scenarios, bind an entire style object:
String Interpolation
Combine static and dynamic styles using template interpolation:
Computed Style Properties
Create dynamic styles based on component state:
Component Styling Strategies
Beyond template bindings, Aurelia provides several approaches for styling components themselves.
Convention-Based Styling
Aurelia automatically imports stylesheets that match your component names:
This means you can focus on writing CSS without worrying about imports:
Shadow DOM
For complete style isolation, use Shadow DOM:
Shadow DOM Configuration Options:
Shadow DOM Special Selectors
Shadow DOM provides special CSS selectors for enhanced styling control:
Global Shared Styles in Shadow DOM
To share styles across Shadow DOM components, configure shared styles in your application:
CSS Modules
CSS Modules provide scoped styling by transforming class names to unique identifiers at build time. Aurelia provides the cssModules() helper to integrate CSS Modules with your components:
The cssModules() helper transforms class names in your template at compile time. In the example above, class="title" becomes class="title_abc123".
Key features:
Works with static classes,
class.bind, and interpolation (class="some ${myClass}")Supports multi-class binding syntax (
class1,class2.class="condition")Each component must register its own
cssModules()- mappings do not inherit to child components
For more details on using CSS Modules with Shadow DOM, see the Shadow DOM documentation.
Real-World Examples and Patterns
The following examples demonstrate practical applications of class and style binding techniques in common scenarios.
Responsive Design with Dynamic Classes
Theme System with CSS Variables
Loading States with Animations
Complex Form Validation Styling
Performance Tips and Best Practices
Do's and Don'ts
✅ DO:
Use
.classfor simple boolean togglingUse CSS custom properties for theming
Prefer computed getters for complex style calculations
Use Shadow DOM for true component isolation
Cache complex style objects when possible
❌ DON'T:
Inline complex style calculations in templates
Use string concatenation for class names when
.classwill doForget about CSS specificity when using
!importantMix too many styling approaches in one component
Performance Optimization
Troubleshooting Common Issues
"My styles aren't updating!"
Problem: Styles don't change when data changes. Solution: Make sure you're using proper binding syntax and that your properties are observable.
"My CSS classes have weird names!"
Problem: Using CSS Modules and seeing transformed class names. Solution: This is expected behavior! CSS Modules transform class names to ensure uniqueness.
"Shadow DOM is blocking my global styles!"
Problem: Global CSS frameworks aren't working inside Shadow DOM components. Solution: Configure shared styles in your app startup.
Migration and Compatibility
Coming from Aurelia 1?
The syntax is mostly the same, with some improvements:
Browser Support
All binding features work in modern browsers. For older browsers:
Shadow DOM requires a polyfill for older browsers
CSS Modules work everywhere (they're processed at build time)
Summary
This guide has covered the complete range of class and style binding capabilities in Aurelia 2. Key takeaways include:
Basic class binding - Use
.classsyntax for simple boolean togglingMultiple class binding - Leverage comma-separated syntax for related classes
Style property binding - Apply individual CSS properties with
.stylesyntaxAdvanced techniques - Implement complex styling with objects, interpolation, and CSS variables
Component styling - Choose appropriate encapsulation strategies for your use case
These techniques provide the foundation for building maintainable, dynamic user interfaces that respond effectively to application state changes.
Additional Resources: For more information on binding syntax, see the template syntax guide. To understand when styles are applied, refer to the component lifecycles documentation.
Last updated
Was this helpful?