Magento – Magento 2 – Overriding CSS without using !important everywhere

cssfrontendless-cssmagento2theme

I'm working on a Magento 2 site at the moment for a client. Suppose my client's brand is boofar and the theme I'm trying to extend/override is foobar I've set as the parent theme using frontend/Foobarthemes/boofar/theme.xml

<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
<title>Boofar</title>
<parent>Foobarthemes/foobar1</parent>
<media>
    <preview_image>media/preview.jpg</preview_image>
</media>

Then under frontend/Foobarthemes/boofar/web/css/source/_theme.less I've written the CSS code that I want to override. I have also tried this with _extend.less.

.magicmenu {
  .home {
    display: none !important;
  }
  .nav-desktop .level0 .level-top > span {
    font-size: 12px;
    font-weight: normal;
    text-transformation: none;
  }
}

I'm forced to use !important for anything to work here. None of the font and text stuff works in the above code.

Have I not understood the Magento 2 frontend workflow correctly?

Best Answer

You only want to have your styles in the _theme.less file if you want to override the parent theme's _theme.less file. For that file, only one of them is loaded, and it will always be the selected theme if the file exists there. From there, it will use the fallback scheme to find that file and use it.

So in your case, using the _extend.less file is the right file to use.

This is a bit confusing though, as the code that is put into the _extend.less file is loaded last in the when Magento compiles all the styles that exist in the site. So i'm wondering if there is something messing with the load order.

Looking over the way you have it set up, try setting your theme up in a different namespace and not in the same theme. This might not solve the problem, as the way you have your theme set up is the same as Magento has the luma/blank theme set up. But for all the work i have done, i have my vender namespace that then will extend from either a 3rd party theme, or from luma/blank.

The next thing to try would be wrapping your code in the built in media queries. I go into more detail here, but basically it stops your styles from being loaded twice into the styles-l.css and the styles-m.css files.

//
//    Common
//--------------------------------------
& when (@media-common = true) {}  

From there, it all comes down to CSS specificity. If there is something else the is higher then yours, you need to be more specific in your class/id definition in the styles. You might want to post a picture of the DOM structure to show what you are targeting and what is over riding what you are looking to target.

Related Topic