Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add CSS files to Phoenix

I added a navbar.html.eex to my layout folder and this template is rendered from app.html.eex <%= render "navbar.html", conn: @conn, current_user: @current_user %>

in app.css:

@import 'navbar.css';

and it should point to my file: assets/css/navbar.css

But the file does not load, in my browser console I get: GET http://localhost:4000/css/navbar.css net::ERR_ABORTED with a 404 error.

I come from the Rails world and that's how I was used to do but maybe there is another way of doing it in Phoenix. I can't find a nice doc about managing css files in Phoenix so if anybody has some readings to recommend ! I'll be grateful !

like image 765
Uj Corb Avatar asked Sep 08 '25 14:09

Uj Corb


1 Answers

Updated for 2022 - Phoenix version 1.6

As of writing, Phoenix (version 1.6) uses esbuild. You can read about asset management in the phoenix documentation, specifically, you may want to read the section about CSS; here's an excerpt:

esbuild has basic support for CSS. If you import a .css file at the top of your main .js file, esbuild will also bundle it, and write it to the same directory as your final app.js.

You'll notice import "../css/app.css" in app.js in projects created with mix phx.new.


Custom CSS when using Tailwind CSS with Phoenix

If you followed the official guide to setup Tailwind with Phoenix 1.6, esbuild will bundle your JS to priv/static/assets/app.js and any CSS files you import in app.js to priv/static/assets/app.css. The problem is, tailwind will then overwrite priv/static/assets/app.css and you'll lose whatever custom styles you imported in app.js.

To get around this, you could change the name of the output file either esbuild or tailwind generates in config/config.exs and change all references to it, or you could paste your custom CSS directly into app.css, optionally within a tailwind @layer directive if you want modifiers and tree-shaking.

like image 52
orangecaterpillar Avatar answered Sep 10 '25 06:09

orangecaterpillar