Suppose you observe CSS characteristic improvement as carefully as we do right here at CSS-Methods. In that case, you might be like me and keen to make use of many of those wonderful instruments however discover browser help generally lagging behind what may be thought-about “trendy” CSS (no matter which means).
Even when browser distributors all have a sure characteristic launched, customers won’t have the most recent variations!
We will definitely plan for this quite a few methods:
- characteristic detection with
@helps
- progressively enhanced designs
- polyfills
For even further assist, we flip to construct instruments. Likelihood is, you’re already utilizing some type of construct software in your tasks right this moment. CSS builders are almost certainly accustomed to CSS pre-processors (reminiscent of Sass or Much less), however in case you don’t know, these are instruments able to compiling many CSS information into one stylesheet. CSS pre-processors assist make organizing CSS lots simpler, as you possibly can transfer components of CSS into associated folders and import issues as wanted.
Pre-processors don’t simply present organizational superpowers, although. Sass gave us a loopy listing of options to work with, together with:
- extends
- capabilities
- loops
- mixins
- nesting
- variables
- …extra, most likely!
For some time, this massive characteristic set supplied a method of filling gaps lacking from CSS, making Sass (or no matter preprocessor you fancy) really feel like a necessity when beginning a brand new venture. CSS has advanced lots because the launch of Sass — now we have so lots of these options in CSS right this moment — so it doesn’t fairly really feel that method anymore, particularly now that now we have native CSS nesting and customized properties.
Together with CSS pre-processors, there’s additionally the idea of submit-processing. This kind of software normally helps remodel compiled CSS in numerous methods, like auto-prefixing properties for various browser distributors, code minification, and extra. PostCSS is the large one right here, supplying you with tons of how to control and optimize your code, one other step within the construct pipeline.
In lots of implementations I’ve seen, the construct pipeline usually runs roughly like this:
- Generate static property
- Construct utility information
- Bundle for deployment
CSS is normally dealt with in that first half, which incorporates operating CSS pre- and post-processors (although post-processing may additionally occur after Step 2). As talked about, the continued evolution of CSS makes it much less vital for a software reminiscent of Sass, so we would have a chance to avoid wasting time.
Vite for CSS
Awarded “Most Adopted Know-how” and “Most Beloved Library” from the State of JavaScript 2024 survey, Vite definitely appears to be one of many extra widespread construct instruments obtainable. Vite is especially used to construct reactive JavaScript front-end frameworks, reminiscent of Angular, React, Svelte, and Vue (made by the identical developer, in fact). Because the identify implies, Vite is loopy quick and could be as easy or advanced as you want it, and has change into one in all my favourite instruments to work with.
Vite is usually regarded as a JavaScript software for JavaScript tasks, however you should utilize it with out writing any JavaScript in any respect. Vite works with Sass, although you continue to want to put in Sass as a dependency to incorporate it within the construct pipeline. However, Vite additionally mechanically helps compiling CSS with no further steps. We will manage our CSS code how we see match, with no or very minimal configuration vital. Let’s test that out.
We might be utilizing Node and npm to put in Node packages, like Vite, in addition to instructions to run and construct the venture. When you wouldn’t have node
or npm
put in, please try the obtain web page on their web site.
Navigate a terminal to a secure place to create a brand new venture, then run:
npm create vite@newest
The command line interface will ask a number of questions, you possibly can hold it so simple as doable by selecting Vanilla
and JavaScript
which is able to offer you a starter template together with some no-frameworks-attached HTML, CSS, and JavaScript information to assist get you began.
Earlier than operating different instructions, open the folder in your IDE (built-in improvement surroundings, reminiscent of VSCode) of selection in order that we are able to examine the venture information and folders.
If you need to observe together with me, delete the next information which can be pointless for demonstration:
property/
public/
src/
.gitignore
We should always solely have the next information left in out venture folder:
index.html
bundle.json
Let’s additionally substitute the contents of index.html
with an empty HTML template:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta identify="viewport" content material="width=device-width, initial-scale=1.0" />
<title>CSS Solely Vite Venture</title>
</head>
<physique>
<!-- empty for now -->
</physique>
</html>
One final piece to arrange is Vite’s dependencies, so let’s run the npm set up command:
npm set up
A brief sequence will happen within the terminal. Then we’ll see a brand new folder known as node_modules/
and a package-lock.json
file added in our file viewer.
node_modules
is used to accommodate all bundle information put in via node bundle supervisor, and permits us to import and use put in packages all through our purposes.package-lock.json
is a file normally used to ensure a improvement staff is all utilizing the identical variations of packages and dependencies.
We almost certainly gained’t want to the touch this stuff, however they’re vital for Node and Vite to course of our code in the course of the construct. Contained in the venture’s root folder, we are able to create a types/
folder to include the CSS we’ll write. Let’s create one file to start with, fundamental.css
, which we are able to use to check out Vite.
├── public/
├── types/
| └── fundamental.css
└──index.html
In our index.html
file, contained in the <head>
part, we are able to embrace a <hyperlink>
tag pointing to the CSS file:
<head>
<meta charset="UTF-8" />
<hyperlink rel="icon" sort="picture/svg+xml" href="/vite.svg" />
<meta identify="viewport" content material="width=device-width, initial-scale=1.0" />
<title>CSS Solely Vite Venture</title>
<!-- Foremost CSS -->
<hyperlink rel="stylesheet" href="types/fundamental.css">
</head>
Let’s add a little bit of CSS to fundamental.css
:
physique {
background: inexperienced;
}
It’s not a lot, but it surely’s all we’ll want for the time being! In our terminal, we are able to now run the Vite construct command utilizing npm
:
npm run construct
With every thing linked up correctly, Vite will construct issues primarily based on what is out there inside the index.html
file, together with our linked CSS information. The construct might be very quick, and also you’ll be returned to your terminal immediate.
The newly generated dist/
folder is Vite’s default output listing, which we are able to open and see our processed information. Testing property/index.css
(the filename will embrace a singular hash for cache busting), and also you’ll see the code we wrote, minified right here.
Now that we all know how one can make Vite conscious of our CSS, we’ll most likely need to begin writing extra CSS for it to compile.
As fast as Vite is with our code, consistently re-running the construct command would nonetheless get very tedious. Fortunately, Vite gives its personal improvement server, which features a dwell surroundings with sizzling module reloading, making modifications seem immediately within the browser. We will begin the Vite improvement server by operating the next terminal command:
npm run dev
Vite makes use of the default community port 5173
for the event server. Opening the http://localhost:5137/
tackle in your browser will show a clean display screen with a inexperienced background.
Including any HTML to the index.html
or CSS to fundamental.css
, Vite will reload the web page to show modifications. To cease the event server, use the keyboard shortcut CTRL+C or shut the terminal to kill the method.
At this level, you just about know all it’s essential learn about how one can compile CSS information with Vite. Any CSS file you hyperlink up might be included within the constructed file.
Organizing CSS into Cascade Layers
One of many objects on my 2025 CSS Wishlist is the power to apply a cascade layer to a hyperlink
tag. To me, this may be useful to prepare CSS in a significant methods, in addition to high-quality management over the cascade, with the advantages cascade layers present. Sadly, it is a quite troublesome ask when contemplating the best way browsers paint types within the viewport. This kind of performance is being mentioned between the CSS Working Group and TAG, but it surely’s unclear if it’ll transfer ahead.
With Vite as our construct software, we are able to replicate the idea as a approach to manage our constructed CSS. Contained in the fundamental.css
file, let’s add the @layer at-rule to set the cascade order of our layers. I’ll use a few layers right here for this demo, however be happy to customise this setup to your wants.
/* types/fundamental.css */
@layer reset, layouts;
That is all we’ll want inside our fundamental.css
, let’s create one other file for our reset. I’m a fan of my good friend Mayank‘s trendy CSS reset, which is out there as a Node bundle. We will set up the reset by operating the next terminal command:
npm set up @acab/reset.css
Now, we are able to import Mayank’s reset into our newly created reset.css
file, as a cascade layer:
/* types/reset.css */
@import '@acab/reset.css' layer(reset);
If there are another reset layer stylings we need to embrace, we are able to open up one other @layer reset
block inside this file as nicely.
/* types/reset.css */
@import '@acab/reset.css' layer(reset);
@layer reset {
/* customized reset types */
}
This @import
assertion is used to tug packages from the node_modules
folder. This folder shouldn’t be usually obtainable within the constructed, public model of an internet site or utility, so referencing this may trigger issues if not dealt with correctly.
Now that now we have two information (fundamental.css
and reset.css
), let’s hyperlink them up in our index.html
file. Contained in the <head>
tag, let’s add them after <title>
:
<head>
<meta charset="UTF-8" />
<hyperlink rel="icon" sort="picture/svg+xml" href="/vite.svg" />
<meta identify="viewport" content material="width=device-width, initial-scale=1.0" />
<title>CSS Solely Vite Venture</title>
<hyperlink rel="stylesheet" href="types/fundamental.css">
<hyperlink rel="stylesheet" href="types/reset.css">
</head>
The thought right here is we are able to add every CSS file, within the order we want them parsed. On this case, I’m planning to tug in every file named after the cascade layers setup in the principle.css file. This may occasionally not work for each setup, however it’s a useful method to remember the priority of how cascade layers have an effect on computed types when rendered in a browser, in addition to grouping equally related information.
Since we’re within the index.html
file, we’ll add a 3rd CSS <hyperlink>
for types/layouts.css
.
<head>
<meta charset="UTF-8" />
<hyperlink rel="icon" sort="picture/svg+xml" href="/vite.svg" />
<meta identify="viewport" content material="width=device-width, initial-scale=1.0" />
<title>CSS Solely Vite Venture</title>
<hyperlink rel="stylesheet" href="types/fundamental.css">
<hyperlink rel="stylesheet" href="types/reset.css">
<hyperlink rel="stylesheet" href="types/layouts.css">
</head>
Create the types/layouts.css
file with the brand new @layer layouts
declaration block, the place we are able to add layout-specific stylings.
/* types/layouts.css */
@layer layouts {
/* layouts types */
}
For some fast, simple, and superior CSS snippets, I are likely to consult with Stephanie Eckles‘ SmolCSS venture. Let’s seize the “Smol intrinsic container” code and embrace it inside the layouts
cascade layer:
/* types/layouts.css */
@layer layouts {
.smol-container {
width: min(100% - 3rem, var(--container-max, 60ch));
margin-inline: auto;
}
}
This highly effective little, two-line container makes use of the CSS min()
perform to supply a responsive width, with margin-inline: auto;
set to horizontally heart itself and include its baby components. We will additionally dynamically regulate the width utilizing the --container-max
customized property.
Now if we re-run the construct command npm run construct
and test the dist/
folder, our compiled CSS file ought to include:
- Our cascade layer declarations from
fundamental.css
- Mayank’s CSS reset totally imported from
reset.css
- The
.smol-container
class added fromlayouts.csss
As you possibly can see, we are able to get fairly far with Vite as our construct software with out writing any JavaScript. Nonetheless, if we select to, we are able to lengthen our construct’s capabilities even additional by writing only a little bit of JavaScript.
Submit-processing with LightningCSS
Lightning CSS is a CSS parser and post-processing software that has loads of good options baked into it to assist with cross-compatibility amongst browsers and browser variations. Lightning CSS can remodel loads of trendy CSS into backward-compatible types for you.
We will set up Lightning CSS in our venture with npm
:
npm set up --save-dev lightningcss
The --save-dev
flag means the bundle might be put in as a improvement dependency, because it gained’t be included with our constructed venture. We will embrace it inside our Vite construct course of, however first, we might want to write a tiny little bit of JavaScript, a configuration file for Vite. Create a brand new file known as: vite.config.mjs
and inside add the next code:
// vite.config.mjs
export default {
css: {
transformer: 'lightningcss'
},
construct: {
cssMinify: 'lightningcss'
}
};
Vite will now use LightningCSS to rework and minify CSS information. Now, let’s give it a check run utilizing an oklch
shade. Inside fundamental.css
let’s add the next code:
/* fundamental.css */
physique {
background-color: oklch(51.98% 0.1768 142.5);
}
Then re-running the Vite construct command, we are able to see the background-color
property added within the compiled CSS:
/* dist/index.css */
physique {
background-color: inexperienced;
background-color: shade(display-p3 0.216141 0.494224 0.131781);
background-color: lab(46.2829% -47.5413 48.5542);
}
Lightning CSS converts the colour white offering fallbacks obtainable for browsers which could not help newer shade varieties. Following the Lightning CSS documentation for utilizing it with Vite, we are able to additionally specify browser variations to focus on by putting in the browserslist
bundle.
Browserslist will give us a approach to specify browsers by matching sure circumstances (strive it out on-line!)
npm set up -D browserslist
Inside our vite.config.mjs
file, we are able to configure Lightning CSS additional. Let’s import the browserslist
bundle into the Vite configuration, in addition to a module from the Lightning CSS bundle to assist us use browserlist
in our config:
// vite.config.mjs
import browserslist from 'browserslist';
import { browserslistToTargets } from 'lightningcss';
We will add configuration settings for lightningcss
, containing the browser targets primarily based on specified browser variations to Vite’s css
configuration:
// vite.config.mjs
import browserslist from 'browserslist';
import { browserslistToTargets } from 'lightningcss';
export default {
css: {
transformer: 'lightningcss',
lightningcss: {
targets: browserslistToTargets(browserslist('>= 0.25%')),
}
},
construct: {
cssMinify: 'lightningcss'
}
};
There are many methods to increase Lightning CSS with Vite, reminiscent of enabling particular options, excluding options we gained’t want, or writing our personal customized transforms.
// vite.config.mjs
import browserslist from 'browserslist';
import { browserslistToTargets, Options } from 'lightningcss';
export default {
css: {
transformer: 'lightningcss',
lightningcss: Options.Colours,
},
construct: {
cssMinify: 'lightningcss'
}
};
For a full listing of the Lightning CSS options, try their documentation on characteristic flags.
Is any of this vital?
Studying via all this, you might be asking your self if all of that is actually vital. The reply: completely not! However I believe you possibly can see the advantages of accessing partialized information that we are able to compile into unified stylesheets.
I doubt I’d go to those lengths for smaller tasks, nonetheless, if constructing one thing with extra complexity, reminiscent of a design system, I would attain for these instruments for organizing code, cross-browser compatibility, and totally optimizing compiled CSS.
Compiling CSS With Vite and Lightning CSS initially revealed on CSS-Methods, which is a part of the DigitalOcean household. You need to get the e-newsletter.
Subscribe to MarketingSolution.
Receive web development discounts & web design tutorials.
Now! Lets GROW Together!