Graham Swan
Graham Swan

Reputation: 4838

How do I handle independent parent and child opacities when the child element is a link?

I have a parent <div> and a child <a>. The parent has a background image set to 60% opacity, but I'd like the child link to have 100% opacity. My reason for implementing it this way is so I can fade the parent's opacity to 100% on hover, thereby eliminating the need for a hover image.

I understand that children inherit their parent's opacity. I tried the :after {} technique described here, but even with appropriate z-index values set, the child link still sits beneath the parent element and is not clickable.

My issue is that the child link cannot be clicked because the parent's :after pseudo-element sits above the child.

My code is as follows:

<div>
  <a href="#">Load more</a>
</div>

div {
  position: relative;
  height: 300px;
} 
div:after {
  position: absolute;
  top: 0;
  left: 0;
  content: '';
  background: url('../img/bg-load-more.png') repeat-x;
  width: 100%;
  height: 300px;
  z-index: 10;
  opacity: 0.4;
}
div a {
  display: block;
  z-index: 100;
}

Does anyone know of a solution to this issue, or must I create an image sprite and switch swap background images on hover?

Upvotes: 0

Views: 272

Answers (1)

Misanthrope
Misanthrope

Reputation: 117

The problem is that you aren't applying a position to the <a> itself (z-index only applies to positioned elements) only the containing div and the pseudo-element, so the pseudo-element is sitting on top of the link preventing it from being clicked.

All you need to do is give the link a stacking context, e.g. include relative positioning:

div a {
display: block;
position: relative;
z-index: 100;
}

Example

Upvotes: 1

Related Questions