How to apply CSS to HTML element before and after text?

3

Considering the HTML code below, is there any way to use only CSS to apply different style to the i element before the text and the other i element after the text?

<a href="#">
  <i class="i i--icon"></i>
  Text
  <i class="i i--icon"></i>
</a>

I could apply a span to the text and easily solve this, but I wonder if there is a way to do this without adding more HMTL code.

Thank you.

    
asked by anonymous 11.10.2015 / 13:57

3 answers

2

I made a small modification to @Chun's response that ended up serving exactly what I needed:

.i--icon {
  &:nth-child(1) {
    margin-right: .5rem;
  }

  &:nth-last-child(1) {
    margin-left: .5rem;
  }
}

I followed the guidelines of CSS Protips .

    
11.10.2015 / 15:02
3

Yes, there is. You can do this using the :nth-child() selector. Here is an example below:

i {color:black; font-size: 25px;}
i:nth-child(2) {color: red;}

a {text-decoration: none;}
<a href="#">
  <i class="i i--icon">#</i>
  Text
  <i class="i i--icon">#</i>
</a>

In this example, the CSS code is immediately pointing directly to the i element because in this excerpt of HTML code there is no parent class to point in a more precise way to the element we want to modify. But in a real project a class parent should be implemented to have more control over what we want to modify and the code would look something like this: link

  

You can read more about :nth-child() at: CSS3: nth-child () Selector

    
11.10.2015 / 14:44
1

You can use pseudo elements ::after and #

So you avoid unnecessary markup in HTML and you do not have to opt to use the% com_of% you commented, which has no relevance to the document because it is only a visual element.

a { text-decoration: none; color: #333 }

a::after,
a::before {
    content: ' ■ '
}

a::after  { color: #2ecc71 }
a::before { color: #8e44ad }
<a href='#'>stackoverflow</a>
    
11.10.2015 / 18:18