September 26, 2014

How to add opacity to div without applying to the contents in it?

How to add opacity to div without applying to the contents in it

Whenever i tried to add opacity to a div container, the opacity is also added to the contents in it. Where the visibility of the content also reduces.

If you need to add opacity to the div container alone i have a solution which will help you out.

I will explain with an example. The example contains div container, box1 and box2. The box1 shows opacity added to both the div container and the contents(paragraph and image), where you can see the background image as the opacity is added. The box2 shows the opacity added to the div container alone. You can see opacity is not added to the contents(paragraph and image). Check out the demo.

HTML

<!-- Opacity is added to the div and to the contents in it -->
<div class="box1">
  <p>Opacity is added to content also</p>  
  <img src="https://sites.google.com/site/vivinantony/img/posts/How-to-add-opacity-to-div-without-applying-to-the-contents-in-it.jpg">
</div>

<!-- Opacity is added only to the div container and not to the contents in it-->
<div class="box2">
  <p>Opacity is added div container alone</p>  
  <img src="https://sites.google.com/site/vivinantony/img/posts/How-to-add-opacity-to-div-without-applying-to-the-contents-in-it.jpg">
</div>

CSS

body {
  background: url(https://sites.google.com/site/vivinantony/img/other/congruent_pentagon.png);
}

.box1 {
  background-color: #000;
  width: 300px;
  height: 200px;
  padding: 20px;
  margin: 30px auto;
  color: #fff;
  opacity: 0.5  
}
.box1 img {
  max-width: 100%;
}

.box2 {
  background-color: rgba(0,0,0,0.5);
  width: 300px;
  height: 200px;
  padding: 20px;
  margin: 30px auto;
  color: #fff
}
.box2 img {
  max-width: 100%;
}

This is achieved by adding background color by RGB and adding opacity to the background color. background-color: rgba(0,0,0,0.5);

This sounds easy know. Try it !

demo

No comments:

Post a Comment

Popular Posts

Views