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

Asked

Viewed 586 times

3

Taking into account the HTML code below, is there any way using only CSS to apply different style to the element i before the text and the other element i after the text?

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

Could apply a span to the text and easily resolve it, but would like to know if there is a way to do this without adding more HMTL code.

Thank you.

3 answers

3

Yes, there is. You can do this using the selector :nth-child(). 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 above, the CSS code is directly pointing to the element i because in this snippet of HTML code there is no class parent to point more precisely to the element we want to modify. But in a real project a class should be implemented Parent to have more control over what we want to modify and the code would look something like this: http://jsfiddle.net/z85zhace/

You can read more about the :nth-child() in: CSS3 :Nth-Child() Selector

  • 1

    Cool, I didn’t think it would be possible using the :nth-child(). Thank you @Chun!

2


I made a small modification in @Chun’s reply 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.

1

You can use the pseudo elements ::after and ::before to style the content before and after an element respectively.

Thus you avoid unnecessary markup in HTML and do not need to choose to make use of span that commented, which has no relevance to the document because it is only an element of a "visual nature".

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.