DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Trending

  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  • The Role of Functional Programming in Modern Software Development
  • SQL Server Index Optimization Strategies: Best Practices with Ola Hallengren’s Scripts
  • Rust and WebAssembly: Unlocking High-Performance Web Apps

CSS Layers Tutorial: Real CSS Encapsulation

In this tutorial, let's take a look at a new feature coming to CSS - CSS layers that are going to change how we write CSS and do real CSS encapsulation.

By 
Johnny Simpson user avatar
Johnny Simpson
DZone Core CORE ·
Updated Apr. 13, 22 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
10.5K Views

Join the DZone community and get the full member experience.

Join For Free

Just around the corner, a new feature is rearing its head and it's getting frontend developers excited. That feature is CSS layers. With layers, we'll finally be able to fully encapsulate our CSS for import. That means modules, scripts, or anything else imported into your projects can have CSS that is entirely separate from your own, putting to bed the age-old problem of styles overriding each other. It will also let us be more agile with the CSS we add to our pages with custom import statements.

Let's take a deep dive into CSS layers, and how they will work when they land in a browser near you.

Support 

CSS layers are currently supported in the latest versions of Firefox and Chrome, with Safari soon to support it in its next release.

Full, up to date support can be viewed below:

So, How Do Layers Work?

Layers outcompete any other precedence within your CSS document. You may be familiar with the concept that an id # selector overrides a class. selector. Layers are stronger than any other selector - so a layer at the bottom of your document will automatically take precedence and override styles elsewhere.

Layers follow the same principle syntax as other block statements in CSS. As such, we can define a new layer like this:

CSS
 
@layer myLayer {

}


Everything within the curly brackets will relate to "myLayer". As you can imagine, we can put any kind of CSS within a layer. So I could do something like this:

CSS
 
@layer myLayer {
    p {
        color: red;
    }
    @media screen and (min-width: 100px) {
        a { color: blue; }
    }
}


And of course, we can define multiple layers one after another, as so. You may also define anonymous layers, which have no names. Note that in the next example, #id.class will render blue, since myOtherLayer comes last, despite myLayer having a higher specificity.

CSS
 
@layer myLayer {
    div #id.class {
        color: red;
    }
}
@layer myOtherLayer {
    #id.class {
        color: blue;
    }
}
@layer oneMoreLayer {}
@layer {}


And finally, layers can be put into layers, and layers with the same name within the same layer or at the top level of your CSS document automatically merge:

CSS
 
css Copy
@layer myLayer {
    @layer mySubLayer {

    }
}

@layer myLayer {
    /* this is the same as the previous "myLayer" - CSS automatically considers them one layer */
}


Setting Layer Order Upfront 

As well as the benefits of being able to fully encapsulate your code with layers, you can tell the browser straight away in which order layers should go in. As with all things CSS, what comes last has the highest importance. So the below example gives the highest importance to styles in myLayer, meaning the selected HTML element will render red.

CSS
 
@layer oneMoreLayer, myOtherLayer, myLayer;
@layer myLayer {
    div #id.class {
        color: red;
    }
}
@layer myOtherLayer {
    #id.class {
        color: blue;
    }
}
@layer oneMoreLayer {}


This makes CSS ultimately so much more powerful - imagine importing a CSS library that no longer has to worry about other CSS you have in your code. It can easily insert itself to the end of your document as a single layer, which acts by itself!

How to Import a CSS File Into a New Layer

CSS layers also allow us to import entire stylesheets into a new layer. The below code imports dropdown-styles.css into the layer midnightDropdownLayer.

CSS
@import url('dropdown-styles.css') layer(midnightDropdownLayer);


Conclusion 

CSS Layers are going to change how we write code and give us new features which will make encapsulation of projects really easy. Ultimately, new features like layers will fuel a whole new set of post-processing and front-end web technology which will change how we build websites today.

If you're interested in learning a bit more, follow the links I've added below:

  • The CSS layer specification
  • CSS Layer thoughts from Miriam Suzanne

Published at DZone with permission of Johnny Simpson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!