Laravel 10: How to Use the New @style
Blade Attribute
Laravel 10 introduced a new Blade directive called @style
, which allows you to conditionally apply inline styles more cleanly and expressively—without cluttering your Blade files with multiple @if
/@else
blocks.
Let’s walk through how it works and how it simplifies style management directly in your Blade templates.
Note: This feature is available from Laravel 10.0 onwards.
Table of Contents
1. Why Use @style
?
Before Laravel 10, if you wanted to conditionally apply inline styles, you'd typically use Blade conditionals (@if
, @else
) and duplicate HTML elements. This can quickly become verbose and hard to maintain.
Laravel 10 introduces the @style
directive, allowing you to inline styles more cleanly, even with conditional logic.
2. Example 1 – Traditional @if
Style Handling
Here’s how we used to conditionally apply styles before:
While this works, it duplicates the <span>
tag and bloats your Blade file.
3. Example 2 – Using @style
For Cleaner Conditional Styles
Now with Laravel 10, you can write the same logic much more cleanly using @style
:
Output:
As you can see, Laravel will intelligently evaluate the conditions and apply the correct styles inline.
Final Thoughts
The @style
Directive is a powerful enhancement to Blade templates that allows for clean, readable, and dynamic inline styles. It’s especially helpful in situations where the logic is simple but the style needs to be conditionally applied.
Thanks for being so supportive! Keep exploring Laravel's awesome features.