Styling Magento Layout Containers with Tailwind CSS
Magento's layout XML containers can be rendered as HTML elements using the htmlTag and htmlClass attributes. This allows applying Tailwind CSS classes directly to structural container elements without creating custom templates.
However, using Tailwind classes in layout XML presents two challenges: Magento's XML schema restricts which characters are allowed in class names, and Tailwind's content scanning must be configured to include XML files.
How Container HTML Attributes Work
When a Magento layout XML container includes the htmlTag attribute, Magento renders the container 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 restricts the characters allowed in htmlClass values. Many Tailwind utility classes contain characters like /, :, [, ], and . that violate the schema pattern, causing validation errors:
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
A pull request to fix this issue was merged in February 2023 but has not been included in all Magento releases. Apply the following patch to allow Tailwind class names in layout XML (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
Instead of applying Tailwind classes in layout XML, define custom styles in your theme's web/tailwind/theme/page-layout.css file. This file is specifically designed for page structure styling and avoids XML schema validation issues entirely.
For example, instead of:
Add to page-layout.css:
This approach keeps structural styles in CSS where they are easier to maintain and avoids potential Magento version compatibility issues with XML schema patches.
Making Tailwind Aware of Classes in Layout XML
Hyvä version 1.2.x and later include layout XML files in the Tailwind content path by default, so classes in XML files are automatically detected during stylesheet generation.
For projects using Hyvä 1.0.x or 1.1.x, manually add layout XML patterns to your Tailwind content configuration to ensure classes used in XML files are included in the production stylesheet.