Add Inline Style to Element in Magento 2 XML

magento-2.1stylesxml

How do I apply an inline style to an element in an XML layout file in Magento 2?

<container name="header.container" as="header_container" label="Page Header Container" htmlTag="header" htmlClass="header" before="main.content"/>

I am looking to add inline styles to the header element above, but I cannot find any reference on how to do this, I tried htmlStyle and this does not appear to work.

Best Answer

According to my research, you can't set inline style on a container element.

The Arguments

  • In the classes responsible for interpreting this type of xml element, Magento\Framework\View\Layout\Reader\Container and Magento\Framework\View\Layout\Generator\Container, you'll find the names of container options in layout, which are used for performing validations:

    const CONTAINER_OPT_HTML_TAG = 'htmlTag'; const CONTAINER_OPT_HTML_CLASS = 'htmlClass'; const CONTAINER_OPT_HTML_ID = 'htmlId'; const CONTAINER_OPT_LABEL = 'label';

  • Also, when the xml's are converted into html output, in Magento\Framework\View\Layout, you'll find in _renderContainer($name) method, this line $html = sprintf('<%1$s%2$s%3$s>%4$s</%1$s>', $htmlTag, $htmlId, $htmlClass, $html);, which means that only tags, ids and classes are included in the html output.

The arguments are strengthened by magento documentation: http://devdocs.magento.com/guides/v2.0/frontend-dev-guide/layouts/xml-instructions.html#fedg_layout_xml-instruc_ex_cont, which presents the allowed options for a container element, without specifying any inline customisations.

The only option I can see is to use htmlClass. If there's a way to do that and I'm wrong, please leave a comment

Related Topic