Comments On Code

Sept 11, 2015

Styling If Parent Contains More than One

See that up there ^ ? That comma separated list of tags? That list is dynamically generated, but I wanted commas to be added if there were more than one tag or category. Sometimes such simple seeming ideas need hacky ways of manipulating CSS to get them done. Inserting commas is a piece of cake (mmmm, cake. Did I mention today is my birthday?). But if I have the potential to have a single item or a list of items, and I only want the commas generated when there are two or more, that is more complicated. This process involves setting a style on all of them, and then over-riding the style with the :only-child selector. Later on, I realized that I really don't want the comma on the last item in the list, so instead I am using the :last-child selector.

The Code: Two Ways

Place the commas: using class term on the parent of our list of anchors, we can insert a comma after the link text of every anchor using the :after pseudo-element.

.term a:after {

content: ',';

color: $charcoal;

}

Clear the comma on only children:

.term li:only-child a:after {

content: ' ';

}

Clear the comma on the last child (which will also clear only children):

.term li:last-child a:after {

content: ' ';

}

Simply write a space on the pseudo-element content instead of a comma. Sending empty content, '', will not clear the comma, but a space between the quotes will.

And there you have it. No comma on single values, and comma separated multiple values.

See the Pen Generated content separators for single and many items by Bekah Sealey (@bekahsealey) on CodePen.