user1251698
user1251698

Reputation: 2143

CSS: Setting background opacity without rgba

In the following code, I want to set the opacity only for the background color of the li (not the text). However, it is important NOT to use the rgba for the background.

I'm trying following, but it sets the opacity for the link text as well.

HTML:

<ul>
    <li><a href="#">Hello World</a></li>
</ul>

CSS:

body{
    background: red;
}

ul{
    margin: 100px;
}

li{
    padding: 10px;
    background: #000000;
    opacity: 0.1;
}

a{
    color: #fff;
    font-weight: 700;
    opacity: 1;  
}

JSFiddle: http://jsfiddle.net/2uJhL/

Upvotes: 13

Views: 15243

Answers (4)

Almir Campos
Almir Campos

Reputation: 3019

Fortunately, the new versions of Chrome and Firefox support 8 digit colors.

For example:

background-color: #ff0000;  (Red)

If you want a opacity of 0.5, you can do this:

background-color: #ff00007f (The 7F is half of FF)

So, from now on you won't need to use the rgba() if you don't want or have the entire div fade away - because of the opacity: 0.x - when you only want the background color a little bit transparent.

But remember that not all browsers support that. So, please test the snippet below on Chrome or Firefox.

<div style="background-color: #ff00003f;">better than [opacity: 0.25]</div>
<div style="background-color: #ff00007f;">better than [opacity: 0.50]</div>
<div style="background-color: #ff0000bf;">better than [opacity: 0.75]</div>
<div style="background-color: #ff0000ff;">better than [opacity: 1.00]</div>

Source:

Upvotes: 9

nmfzone
nmfzone

Reputation: 2903

tl;dr Cmiiw, you can't setting the background opacity without RGBA

Let me try to give another solution.

This solution is not the real answer for the problem, but it may helps.

For me, you just need to convert the background color (hex value) to RGBA, using tools something like this https://cssgenerator.org/rgba-and-hex-color-generator.html.

Then, just use the RGBA value in your background color.

Upvotes: 0

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35963

The opacity is applied at the content and all children. You can't set a different opacity for the children. However if you don't want to use rgba you can use a png with opacity that you want. And setting a png to your li in the background is the best solution in this case

Upvotes: 1

Simone
Simone

Reputation: 21262

You can set a PNG or GIF image as background, i.e:

li { 
  background-image: url('path/to/your/image.png'); 
}

Upvotes: 2

Related Questions