CSS Tips
CSS and HTML keep getting better every year and it seems like last year we got some big improvements.
Introduction
I have recently been getting back into CSS and adapting to all the new changes and relearning some things that can actually be done in CSS and not in HTML and server side code. Here are some of my tips I've learned that I wish I knew earlier that CSS can actually handle for you.
Comma Seperated Lists
You get presented with a list of tags or lsit of names and you need to dynamically create a list and add comma seperated list. But you need the list to have some padding and of course avoid adding a comma on the last name or tag. In Phoenix I would write something like this.
<nav aria-label="Tags" class="tag-list">
<%= for tag <- Enum.intersperse(["a", "b", "c", "d"], ",") do %>
<%= if tag == "," do %>
<span class="text-slate-500"><%= "," %></span>
<% else %>
<.link href={~p"/tags/#{tag}"} title={"See all posts related to #{tag}"}><%= tag %></.link>
<% end %>
<% end %>
</nav>
But with CSS you keep your loop in that template that you had more straight forward like this.
<nav aria-label="Tags" class="tag-list">
<%= for tag <- ["a", "b", "c", "d"] do %>
<.link href={~p"/tags/#{tag}"} title={"See all posts related to #{tag}"}><%= tag %></.link>
<% end %>
</nav>
and then in your CSS you write something like this:
.tag-list a:not(:last-child)::after { // [!code highlight]
content: ",";
margin-right: 0.05em;
}
What this selector does
This one rule does three things:1
- Targets every
<a>inside.tag-listexcept the last one, using:not(:last-child). - Adds a comma after each of those links with
content: ","on the::afterpseudo-element — a virtual element generated after the link's own content. - Nudges the comma over with a small
margin-rightof0.05em.
I am sure this has existed for a while but I had no idea you could combine pseudo-elements with :not(:last-child) like this.
-
The separator lives entirely in the stylesheet, so the markup stays a clean loop with no separator logic. Because
::aftercontent is generated, it is also non-selectable text — the commas won't end up in a copy-paste of the tag list. ↩