Magento – Magento 2.2.2 – Move custom navigation into header-wrapper in XML and make it responsive

magento2navigationxml

Below xml adds custom navigation before category. To make it responsive I have included it under block navigation.sections.

<referenceBlock name="navigation.sections">
             <arguments>
                    <argument name="group_name" xsi:type="string">navigation-sections</argument>
                    <argument name="group_css" xsi:type="string">nav-sections</argument>
                </arguments>
            <block class="Magento\Framework\View\Element\Template" name="sub.nav" group="navigation-sections" template="Magento_Theme::html/header_links.phtml">
                <arguments>
                    <argument name="title" translate="true" xsi:type="string">Sub Nav</argument>
                </arguments>
            </block>
        </referenceBlock>

But now it break my HTML structure as I want this custom block to be inside header.wrapper and at the same time responsive. I tried below but its not working

<move element="sub.nav" destination="header-wrapper" after="logo"/>

Although navigation.sections can be moved into header and its responsive too.

<move element="navigation.sections" destination="header-wrapper" after="logo"/>

If I change referenceBlock to header.wrapper, the navigation goes inside header but then it is not working for responsive mode. How do I move my custom navigation inside header.wrapper and make it responsive also ?

Best Answer

What I did as a workaround is to duplicate the topmenu layout, leaving the original for mobile and the new one for desktop. Then with CSS you can show/hide the desired menu. Something like this:

default.xml

<referenceContainer name="header-wrapper">
  <container name="topmenu.desktop"
    as="topmenu.desktop"
    label="Top Menu - Desktop"
    htmlTag="div"
    htmlClass="topmenu-desktop"
    after="logo">
    <block class="Magento\Theme\Block\Html\Topmenu"
      name="catalog.topnav.desktop"
      template="Magento_Theme::html/topmenu.phtml"
      ttl="3600"/>
  </container>
</referenceContainer>

CSS

/* Hide the original Navigation menu on Desktop */
.nav-sections {
  @media (min-width: @min_tablet) { display: none; }
}

/* Hide the duplicated Navigation menu on Mobile */
.page-header {
  .header.content {
    .topmenu-desktop {
      @media (max-width: @max_tablet) { display: none; }
    }
  }
}

Note: I added the custom links to the Top Menu as explained here, so the links inherit the navigation classes

Hope it helps.