Today I Learned: CSS Layers

As someone who's more proeficient on the backend side of things, CSS has always scared me. The cascade, specificity wars and trying to figure out why a style is not applying feels like black magic. This gets specially more complicated when importing CSS from external tools/libraries you are working with.

Today, after spending some time trying to override the styles of a component from an external library, I learned about a CSS feature that can help with it: @layer!

Layers allow you to write your CSS in a defined hierarcy making it easier to control which stlyes take precedence. I discovered this is really helpful when dealing with imported CSS from external libraries.

Here's an example. Let's say that you are importing CSS from a third party library and you want to override some of its styles without doing any weird CSS hacks. You can import the third party CSS into a specific layer, and then override the styles you need in a high priorty layer:

@layer low_priority, mid_priority, high_priority;

@import url('/path/to/third-party.css') layer(low_priority);

@layer mid_priority {
	.search {
		display: flex;
		/** more stuff here */
	}
}

Here the external CSS is imported into the low_priority layer, and I'm overriding the .search class using the mid_priority layer. Now, you don't need to match external CSS with overly specific selectors or the !importantdeclaration.