1

I'd like have a margin on an element, on the right if the element is the first element of the parent <div>, or on the left if the element is the last element of the parent <div>.

The thing is, there is no other element in the <div>, only plain text.

Here's where I am:

HTML:

<div class="parent">
    <i>&rarr;</i>Action
</div>

<div class="parent">
    Action<i>&larr;</i>
</div>

CSS:

.parent i:first-child {
    margin-right: 5px;
}

.parent i:last-child {
    margin-left: 5px;
}

With the first selector I'm trying to target the first <div>, and with the last selector I'm trying to target the last <div>.

But actually since <i> is the only child element, both rules apply to this element.

See fiddle.

Is there a way I can select the <i> that is at the beginning or the end of the parent, without modifying the markup? (Adding a <span> to wrap the text is not the solution I'm looking for...)

Habovh
  • 457
  • 8
  • 20
  • 1
    CSS doesn't select text nodes so I don't think you will be able to achieve this without wrapping the text in another tag. – Hidden Hobbes Nov 17 '15 at 12:32
  • That's what I wanted to find out... I think I'll need to change the markup then... – Habovh Nov 17 '15 at 12:33
  • 1
    Although you could control the text using `content` on the `:before` or `:after` pseudo selectors. – Paul Redmond Nov 17 '15 at 12:34
  • True, but not the solution I am looking for either... I guess I'll just go with the `` wrapping. – Habovh Nov 17 '15 at 12:42
  • @JordanBecker Is there something in particular you are trying to achieve? Perhaps there is an "out of the box" way to get the result without modifying the markup. – Hidden Hobbes Nov 17 '15 at 13:28
  • I'm trying to add a margin to separate the `` tag from the text. So if the `` tag is placed before the text, I want it to have a margin to the right only. Likewise when the `` tag is after the text, I want it to only have a left margin. – Habovh Nov 17 '15 at 15:00

2 Answers2

1

Based on this question, and on the comments on my original question here, it seems that there is no way to achieve text node selection in CSS.

Therefore to address my issue I have to wrap my text node in an inline element, like <span>, in order for my :first-child and :last-child selectors to work as expected.

See updated fiddle

Community
  • 1
  • 1
Habovh
  • 457
  • 8
  • 20
0
<div class="parent">
     <i>&rarr;</i>Action
</div>

<div class="parent">
    Action<i>&larr;</i>
</div>
<div class="clearfix"></div>


.parent {
    float: left;
}
.parent:first-child {
    margin-right: 5px;
}