Styling Magento Layout Containers with Tailwind CSS
Magento's `htmlTag` and `htmlClass` attributes allow you to render layout XML containers as HTML elements, applying Tailwind CSS classes directly without custom templates.
However, this approach presents two challenges: Magento's XML schema restricts allowed characters in class names, and Tailwind's content scanning needs configuration to include XML files.
How Container HTML Attributes Work
When a Magento layout XML container uses the `htmlTag` attribute, it renders as that HTML element. The `htmlClass` attribute adds a `class` attribute to the rendered element:
This renders as:
XML Schema Validation Errors
Magento's layout XML schema has strict character restrictions for `htmlClass` values. This often causes validation errors when using common Tailwind utility classes that contain characters like `/`, `:`, `[`, `]`, and `.`:
This produces the following error:
Exception #0 (MagentoFrameworkConfigDomValidationException):
Element 'container', attribute 'htmlClass': [facet 'pattern']
The value 'columns order-2 w-1/3' is not accepted by the pattern
'[a-zA-Z][a-zA-Z\d\-_]*(\s[a-zA-Z][a-zA-Z\d\-_]*)*'.
Workaround 1: Patch the Schema Pattern
While a fix was merged in February 2023, it might not be in your Magento release. To enable Tailwind classes in layout XML, apply this patch (contributed by Arjen Miedema):
@package magento/framework
diff --git View/Layout/etc/elements.xsd View/Layout/etc/elements.xsd
index 51f1931..14baa00 100644
--- View/Layout/etc/elements.xsd
+++ View/Layout/etc/elements.xsd
@@ -119,7 +119,7 @@
<xs:simpleType name="htmlClassType">
<xs:restriction base="xs:string">
- <xs:pattern value="[a-zA-Z][a-zA-Z\d\-_]*(\s[a-zA-Z][a-zA-Z\d\-_]*)*"/>
+ <xs:pattern value="[a-zA-Z\d\-_/:.\[\]&@()! ]*"/>
</xs:restriction>
</xs:simpleType>
Workaround 2: Use Custom CSS Instead of Layout XML Classes
Alternatively, avoid XML schema issues by defining custom styles in your theme's `web/tailwind/theme/page-layout.css`. This file is ideal for page structure styling.
For example, instead of:
Add to `page-layout.css`:
This approach keeps structural styles in CSS, improving maintainability and avoiding potential Magento version compatibility issues with XML schema patches.
Making Tailwind Aware of Classes in Layout XML
For Hyvä 1.2.x+, Tailwind automatically detects classes in layout XML files during stylesheet generation.
If you're on Hyvä 1.0.x or 1.1.x, manually add layout XML patterns to your Tailwind content configuration to ensure these classes are included in your production stylesheet.