Enzio
Enzio

Reputation: 387

Positioning :after-pseudo behind text in a link

I was wondering if it's possible to position the z-index of a :after-pseudo element so that it's behind a link's text. For example;

HTML

<a href="#">Here's a link</a>

SCSS

a {
    background: #666:
    height: 40px;
    padding: 0px 20px;
    position: relative;
    color: #FFF;

    &:before {
        /* this is occupied */
    }

    &:after {
        content: "";
        width: 100%;
        height: 100%;
        position: absolute;
        display: block;
        top: 0; left: 0;
        background: #000;
    }
}

What I'm trying to achieve here is to display the link's text. This is currently not happening because the :after element is overlapping it. I'd like to put the text to the front without using something like a <span> tag. Note: it should overlap its original background, but not the text.

Is there a way to achieve this, or is this simply impossible?

Upvotes: 1

Views: 1604

Answers (3)

thepio
thepio

Reputation: 6263

It's as easy as setting the z-index: -1; for the :after pseudo-element.

&:after {
    content: "";
    width: 100%;
    height: 100%;
    position: absolute;
    display: block;
    top: 0; 
    left: 0; 
    z-index: -1; /* Set this */
    background: #000;
}

Here's a JSFiddle: https://jsfiddle.net/thepio/tm9n0x5g/1/

EDIT:

Based on your comment, there is one trick you could use but I don't know if it will go along your animation. You could use a title attribute in the HTML itself and use it as the content of the :after pseudo-element.

a {
  position: relative;
  background: #666;
  height: 40px;
  padding: 0px 20px;
  position: relative;
  color: #FFF;
  z-index: 1;
}
a:after {
  content: attr(title);
  width: 100%;
  height: 100%;
  position: absolute;
  display: block;
  top: 0;
  left: 0;
  background: #000;
  color: white;
  text-align: center;
}
<a href="#" title="Here's a link">Here's a link</a>

Then you can perhaps fade it in/out or whatever you prefer.

Here's a new JSFiddle: https://jsfiddle.net/thepio/tm9n0x5g/1/

Upvotes: 1

Enzio
Enzio

Reputation: 387

I found a proper solution. I'll use a box-shadow: inset 0 -3.125rem 0 #000; on the element instead. This way I don't have to use the :after element.

Thank you all for the comments.

Upvotes: 1

Ahmed Salama
Ahmed Salama

Reputation: 2825

You just need to add z-index:-1; to the :after-pseudo

a {
    background: #666:
    height: 40px;
    padding: 0px 20px;
    position: relative;
    color: #FFF;
}

a:after {
  content: "";
  width: 100%;
  height: 100%;
  position: absolute;
  display: block;
  top: 0; left: 0;
  background: #000;
  z-index:-1;
}
<a href="#">Here's a link</a>

https://jsfiddle.net/d8htv6a9/

Upvotes: 0

Related Questions