Wednesday, February 6, 2013

Non-Transparent Elements Inside Transparent Elements

If using transparency on a block element it makes the text inside transparent as well. Is there a way I can prevent that from happening? I tried putting the text in another div and setting the opacity to 100%, but that didn't do the job. Although, logically, I thought it would!

Code Problem-
HTML
<div class="transparentDiv">
  <h2>Non-Transparent Elements Inside Transparent Elements.</h2>
</div>


CSS
.transparentDiv {
  height: 4em;
  padding-top: 2em;
  opacity: 0.5;
  background: black;
  border-top: 3px solid #ccc;
  border-bottom: 3px solid #ccc;
  margin-top: 5.0em;
}


This is where you notice that the text inside the transparentDiv as taken on the transparency of the transparentDiv itself. You don't want that, it's making the text hard to read! So you get smart and apply 100% transparency to the text inside the div. Doesn't work right?

Trick to resolve the issue-
This is a quick tip to demonstrate a way to work around the problem of child elements in your HTML inheriting the "alpha" settings of their parent.

As you likely know, just because an element occupies the same space as another element, doesn't make one a child of the other. That's the beauty of CSS positioning. So the trick to getting our non-transparent text into a transparent div is just to put that text outside of the div and push it visually inside with some CSS positioning.

HTML:
<h2 class="fullOpacity">Non-Transparent Elements Inside Transparent Elements.</h2>
<div class="transparentDiv"></div>


CSS:
.transparentDiv {
  height: 4em;
  padding-top: 2em;
  opacity: 0.5;
  background: black;
  border-top: 3px solid #ccc;
  border-bottom: 3px solid #ccc;
  margin-top: 5.0em;
}

h2.fullOpacity {
  position: relative;
  top: 4.7em;
}

No comments:

Post a Comment

your comments.....