Modern web development is based on components, whether or not a front-end
framework like Angular or React is used. Combined with wide browser support for
CSS variables, I would argue that it has never been easier to style using plain
CSS.
With that out of the way, Bootstrap is still one of
the most popular CSS frameworks and here is how to use it with Astro.
The key to using Bootstrap efficiently is to include only the CSS you need.
Create a new Sass file that imports the necessary packages:
During development or debugging, you could also temporarily import everything
with:
For more details, see the
Sass page in the official
Bootstrap documentation.
Add Layout and pages
Create a new Astro file that will serve as the main page layout. Same as with
CSS, make sure you import only the JavaScript modules that you need:
During development or debugging, you could also temporarily import everything
with:
To use the layout replace the contents of the index page with the following
Bootstrap example content:
Add more pages using the same <Layout> if you like.
Bootstrap icons
There are many options to include icons. I recommend to use the
official Bootstrap Icons and add the SVG
directly to the Astro/HTML files.
Just head over to their docs, select an icon
that you like, copy the SVG and paste it into your page. No need to
overcomplicate things.
Run the development server
To check the final result run:
Running in production
Only including the CSS and JavaScript that we need, and without any further
optimization, the Lighthouse
score rocks!
This setup can be optimized even more. But don’t overdo it. Simplicity is king.
Set caching header
All files in the dist/_astro folder are compiled by Astro and an hash is
included in the file name. If the content changes the filename will change, too.
Therefore we can tell the browser that it is safe to cache these files forever.
The browser will not even check if there is a new version, making subsequent
page visits blazingly fast.
For the classic Apache webserver that many hosters still use, this can easily be
configured by creating the following file:
Minimize CSS
If you had been exposed to Tailwind for a long time, you will feel the urge to
minify Bootstrap’s CSS. This is totally possible to do, and can easily be
automated with the
astro-purgecss integration .
But in my opinion, it is not worth bringing in a new dependency to your project.
The compiled Bootstrap CSS file is usually really small:
The example we build: 12 kB
The medium-size website I made for my
foosball club: 23 kB