Reputation: 14218
I would like to define colors with opacity I know that it is possible to do this via rgba colors, but I like the ease of named colors. e.g.:
background-color: red;
Is there a way to combine the two?
Upvotes: 1
Views: 713
Reputation: 87191
You can't use "red" in rgba(red,0.5)
with standard CSS, but you can do
background: red;
opacity: 0.5;
The down side is that opacity will affect child elements, which rgba(255,0,0,0.5)
will not.
By using pseudo element you can create a similar effect.
div {
position: relative;
height: 30px;
}
div:first-child {
background: rgba(255,0,0,0.5);
margin-bottom: 10px;
}
div ~ div:before {
content: ' ';
position: absolute;
left: 0; top: 0;
right: 0; bottom: 0;
background: red;
opacity: 0.5;
z-index: -1;
}
<div>Hello</div>
<div>Hello</div>
Upvotes: 1
Reputation: 2885
The CSS3 rgba()
and hsla()
functions are the only way to directly specify a color with alpha. However, if use of less or SASS is allowed, colors can be assigned to variables and used similarly to the builtin named colors. A less example:
@red50: rgba(255, 0, 0, 0.5);
.something {
background-color: @red50;
}
Upvotes: 0
Reputation: 115047
No...this is not possible in raw CSS.
CSS preprocessors however can do this
SASS
div {
width: 100px;
height: 100px;
background-color: rgba(red,0.5);
}
compiles to
CSS
div {
width: 100px;
height: 100px;
background-color: rgba(255, 0, 0, 0.5);
}
Upvotes: 1
Reputation: 65806
The only way would be to apply the color and the opacity separately like this:
someElement {
background: blue;
opacity: .5;
}
But, this won't be possible to do selectively since opacity applies to the entire element, not any one aspect of the element. Here, you'll see that the background color and the font color are both affected.
div { background: yellow;
color:green;
opacity: .5;
}
<div>This is my div</div>
Upvotes: 1
Reputation: 4854
I'm afraid that you can't. There are no named alpha channel colors in the css3 specification.
You can read more about it in https://drafts.csswg.org/css-color-3/#colorunits
If what you want is to have a nemonic to apply to backgrounds, may be the best is to create a class for that:
.red-50 {
background-color: rgba(255, 0, 0, 0.5);
}
.red-75 {
background-color: rgba(255, 0, 0, 0.75);
}
And apply to your html elements
<div class="red-50 someOtherClass"></div>
Upvotes: 0