Change background color transparency on hover

I have a DIV on which I want to change the transparency of the background color, depending on whether the mouse is pointing at it or not.

I know that you can use background: rgba(54, 25, 25, .5), etc., but I want to set the color separately. Is there a way that I can just change the OPACITY, not the color.

I could opacity: 0.3, etc., but it affects the whole DIV, and I just want to affect the background color.

+5
source share
6 answers

There is no html / css, this parameter is not built-in, but since you are accessing / setting the color in javascript, you can add your own function that can handle this.

Here is an example for you:

<script type="text/javascript">
function RGBA(red,green,blue,alpha) {
    this.red = red;
    this.green = green;
    this.blue = blue;
    this.alpha = alpha;
    this.getCSS = function() {
        return "rgba("+this.red+","+this.green+","+this.blue+","+this.alpha+")";
    }
}

// store a copy of the color
var bgColor = new RGBA(255,0,0,0.5);

function setBgOpacity(elem, opac) {
    bgColor.alpha = opac;
    elem.style.backgroundColor = bgColor.getCSS();
}
</script>

HTML onmouseover bgColor:

<div onmouseover="setBgOpacity(this, '0.3');"
     onmousout="setBgOpacity(this, '0.5');">Put your mouse over me</div>
+4

div THAT div, ..

<div id="container">
    <div id="background"></div>
    <div id="content">
        <p>Lorum ipsum...</p>
    </div>
</div>

#container { overflow:hidden; position:relative; }
#background { 
    position:absolute; 
    top:0; 
    left:0; 
    width:100%; 
    height:100%; 
    background:#FF0000;
}
#background:hover { opacity:0.3; }
#content { position:relative; z-index:10; }
+4

Alpha RGBa Opacity. , Alpha .

, RGBa Alpha. .

+2

RGBA, , , . RGBA , .

+1

, rgba. RGB RGBa.

+1

, :before :after.

.container { 
    position: relative;

    &:before {
        content: '';
        position: absolute;
        width: 100%;
        height: 100%;
        background-color: #000;
        opacity: 1;
        z-index: -1;
    }

    &:hover {
        &:before {
            opacity: 0.5;
        }
    }

    .content {
        z-index: 1;
    }
}

When hovering over .container, only opacity is performed :before, not the content.

+1
source

All Articles