Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have a child opacity different then parent opacity with CSS

Tags:

html

css

Here are my box classes

.rectangle-box {
    width: 200px;
    height: 30px;
    background: #808080;
    opacity: 0.3;
    float: right;
}

.rectangle-red {
    width: 65px;
    height: 30px;
    background: #ff4742;
    opacity: 1;
    float: left;
}

In HTML:

<div class="rectangle-box">
    <div class="rectangle-red"></div>
</div>

DEMO: https://jsfiddle.net/uq6ectfc/1/

I need rectangle-red to have opacity of 1 and rectangle-box of 0.3. But it sticks to the parent opacity.

How can I fix it?

like image 731
Michael Avatar asked Nov 30 '22 10:11

Michael


2 Answers

You can't the opacity cannot be greater than parent

but you can use two methods

I have used rgba rgba(0,0,0,0.0)

.rectangle-box {
  width: 200px;
  height: 30px;
  background: rgba(128, 128, 128, 0.3);
  float: right;
  position: relative;
}

.rectangle-red {
  width: 65px;
  height: 30px;
  background: #ff4742;
  opacity: 1;
  float: left;
}
<div class="rectangle-box">
  <div class="rectangle-red"></div>
</div>

Or the second method i have used :pseudo element to add a background

.rectangle-box {
  width: 200px;
  height: 30px;
  float: right;
  position: relative;
}

.rectangle-box:after {
  content: '';
  opacity: 0.3;
  background: #808080;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  z-index:-1;
}

.rectangle-red {
  width: 65px;
  height: 30px;
  background: #ff4742;
  opacity: 1;
  float: left;
}
<div class="rectangle-box">
  <div class="rectangle-red"></div>
</div>
like image 182
Vitorino fernandes Avatar answered Dec 18 '22 18:12

Vitorino fernandes


Use RGBA instead of hex. using opacity: affects child elements and rgba does not

.rectangle-box {
        width: 200px;
        height: 30px;
        background-color: rgba(128,128,128, 0.3);
        float: right;

    }

    .rectangle-red {
        width: 65px;
        height: 30px;
        background-color: rgba(255,71,66, 1);
      float: left;
    } 
like image 24
Ty T. Avatar answered Dec 18 '22 20:12

Ty T.