Magento 2 – Add Block Above Page Header

blocksheadermagento-2.1magento2

I tried to add a simple div into my Magento 2 theme.
I've added this code to

/app/code/design/frontend/MyCompany/MyTheme/Magento_Theme/layout/default.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  <body>
    <referenceContainer name="columns.top">
      <container name="topline" as="topline" htmlTag="div" htmlClass="topline" before="page.header">
        <block class="Magento\Framework\View\Element\Template" name="top.line" template="Magento_Theme::topline.phtml" />
      </container>
    </referenceContainer>
  </body>
</page>

And I added this file with some test content:

/app/code/design/frontend/MyCompany/MyTheme/Magento_Theme/templates/topline.phtml

Of course, I've tried other answers here in StackExchange, but nothing worked. I read that when there's no content, the dom even does not appear – is that correct? But main question: what's wrong with my code? Btw, mage cache cleared.

Best Answer

Change your default.xml to

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="header-wrapper">
            <block class="Magento\Framework\View\Element\Template" name="top.line" template="Magento_Theme::topline.phtml" />
        </referenceContainer>
    </body>
</page>

If you want to add your block to top header change <referenceContainer/> to

<referenceContainer name="header.panel">

Now flush cache and try.