dshamis317
dshamis317

Reputation: 91

Can an :after background-image be used to overlap the next element?

I have an image that I'd like to add as an :after element to a nav bar. The point being that the :after would cover the top portion of the next section (this is part of the design).

The :after is set as position: absolute with a top: 100% and it seems to disappear under the next element and z-index hasn't helped. When the top is set to anything less than 100%, you can see the :after element above the nav.

The markup:

<nav>Contents</nav>
<div>Contents</div>

The CSS:

nav {
    width: 100%;
    position: relative;
}

nav:after {
    content: '';
    width: 100%;
    height: 66px;
    background-image: url('image.png');
    background-repeat: repeat-x;
    position: absolute;
    left: 0;
    top: 100%;
}

No CSS for div yet...

Thanks in advance!

Upvotes: 0

Views: 800

Answers (1)

Paulie_D
Paulie_D

Reputation: 115278

All you need is to set the z-index on the Content div to lower than that of the pseudo-element but note that the Content div must have a position setting on anything other than static...position:relative is usually sufficient.

Alternatively, just set the z-index of the pseudo-element to higher than that of the div (which will probably default to 1).

nav {
  width: 100%;
  position: relative;
  height: 50px;
  background: lightgreen;
}
nav:after {
  content: '';
  width: 100%;
  height: 66px;
  background: rgba(0, 0, 255, 0.5);
  background-repeat: repeat-x;
  position: absolute;
  left: 0;
  top: 100%;
  z-index: 2;
}
div {
  height: 260px;
  position: relative;
  background: rgba(255, 0, 0, 0.5);
}
<nav>Nav</nav>
<div>Contents</div>

Upvotes: 1

Related Questions