Is there a CSS selector for an element with adjacent text?

Viewed 78

Here's what I have:

<a class="button">
    <i class="fa fa-times" />Some button label
</a>

where the <i class="fa fa-times" /> is a Font Awesome icon.

This renders with the icon right next to the text, without any space between them.

I was just adding a margin-right to the i.fa elements, but now I'm in a position where I need to add a button without any text, and the icon is off-center.

I considered i.fa + span to apply a margin-left to the text, but that would require me wrapping the text in a span (and there are a fair number of them sprinkled throughout my code).

I'm doing this in React components and I'd prefer to just update my stylesheets to handle this. If there's no CSS solution, then I'm going to write a Button component to handle it.

Is there a selector which would allow me to select only those i.fa which have text adjacent to them, so I can apply a margin-right and space them out a bit?

2 Answers

I think the best option is to wrap the text in a span tag as you've suggested. You can't target text nodes with CSS.

All is not lost: https://jsfiddle.net/47L4ajgd/

.fa {
  display: inline; /* NOT inline-block! */
}

i::after {
  content: ' '; /* the word spacing itself */
  font-size: 0px;
  word-spacing: 50px; /* set this instead of margin */
}

/* Some styling for demo */
.fa-times::before {
  content: "ICON"; /* Font Not-So-Awesome */
}

a {
  display: inline-block;
  border: 1px solid red;
  margin: 0 20px;
}
<a class="button">
    <i class="fa fa-times"></i>Some button label
</a>
<a class="button">
    <i class="fa fa-times"></i>
</a>
<a class="button">
    Some button label
</a>

Related