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 {
content: ",";
margin-right: 0.05em;
}
This CSS selector and rule does three things:
• Targets all <a> elements within .tag-list except the last one using :not(:last-child).
• Adds a comma after these elements using content: “,” and ::after. ::after is a pseudo-element that creates a virtual element after the content of the selected element.
• Places a small margin (0.05em) after the comma.
I am sure this has existed for awhile but I had no idea that you can combine pseudo-elements and :not and (:last-child) like this.