beeb beeb - 4 months ago 9
CSS Question

CSS selector and content property to add a space character between two inline-block elements

I have a series of

span
elements of class
tag
(from bootstrap v4) which are adjacent to each other without any space between them because they come from a reacj.js array of JSX elements :

<span class="tag tag-primary">text</span><span class="tag tag-primary">text</span><!-- ... -->


This is the CSS from bootstrap:

.tag {
display: inline-block;
padding: 0.25em 0.4em;
font-size: 75%;
font-weight: bold;
line-height: 1;
color: #fff;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: 0.25rem;
}


These elements can wrap over several lines in a table cell. I could add a space character in-between painfully with some javascript (http://stackoverflow.com/a/23619085/3446439), or add a wrapping element (to have only one root element in the JSX) with a space character. Both these options don't satisfy me and I figured it should be simple to do it in CSS.

I tried the following, which would be ideal if it worked, but it doesn't with inline-block elements (https://jsfiddle.net/qjbgzzLr/) :

span.tag + span.tag::before {
content: " ";
}


For now, I put a
margin-left
on
span.tag + span.tag
but this is not ideal since the first element in every line has a margin to its left.

Is there a way to achieve this with CSS only ?

Answer

Any pseudo-element would be inside the span tag and so would not create a horizontal space between tags. Margin is the only solution available to you.

I'd suggest just adding margin-right to each tag.

span.tag {
  margin-right: .25em;
}

span.tag {
  margin-right: .25em;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.3/css/bootstrap.min.css" rel="stylesheet" />

<span class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span
class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span
  class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span class="tag tag-primary">text</span><span
    class="tag tag-primary">text</span>

To remove the margin from the final tag you can use

span:last-of-type {
margin-right:0;
}