Reputation: 769
Is it possible to define opacity in CSS by percentage (eg 30%) in CSS? does not seem to be working, right now I can only conduct it by decimal point.
https://css-tricks.com/almanac/properties/o/opacity/
.test{
opacity: 0.3;
}
Intended Goal:
.test{
opacity: 30%;
}
Upvotes: 8
Views: 8602
Reputation: 3669
Despite what the most popular answer (and Mozilla) say, comments by leoap and Charlie Harding have observed that opacity percentages are not officially supported.
W3 doesn't mention percentages for opacity, and Can I Use shows mixed browser support for it in the real world, outside of recent Chrome, Edge and Firefox.
So if in any doubt about which browsers will see your content, it's best to avoid it and stick with decimals.
Upvotes: 0
Reputation: 426
Using a percentage is fully valid css, according to the spec: https://developer.mozilla.org/en-US/docs/Web/CSS/opacity#Values
alpha-value
Anumber
in the range 0.0 to 1.0, inclusive, or apercentage
in the range 0% to 100%, inclusive, representing the opacity of the channel (that is, the value of its alpha channel). Any value outside the interval, though valid, is clamped to the nearest limit in the range.
So, either of these should be okay, according to spec:
.foo {
opacity: .3;
}
.foo {
opacity: 30%;
}
Keep in mind, though, that if you are using Sass, it will not handle the percentage
value, and will compile it to 1%
.
Upvotes: 14
Reputation: 274272
Yes it's possible if you consider filter
.box {
filter:opacity(30%);
background:red;
height:20px;
}
<div class="box">
</div>
You will even have better performance because:
This function is similar to the more established opacity property; the difference is that with filters, some browsers provide hardware acceleration for better performance.ref
Simply pay attention to some special behavior related to stacking context: CSS-Filter on parent breaks child positioning
Upvotes: 1
Reputation: 6154
If you really want to use a 0 to 100 range, you can calculate the decimal automatically:
element {
opacity: calc(40 / 100);
}
or you can use a variable to make it clearer:
element {
--opacity-percent: 40;
opacity: calc(var(--opacity-percent) / 100);
}
But both of these are less clear than just using a decimal like the standard says, so I wouldn't recommend them unless there's a really valid reason.
Upvotes: 1
Reputation: 208032
No, decimals only.
Any values outside the range 0.0 (fully transparent) to 1.0 (fully opaque) will be clamped to this range.
Upvotes: 0
Reputation: 454
According to the docs, it has to be a number between 0 and 1.
https://developer.mozilla.org/en-US/docs/Web/CSS/opacity https://www.w3schools.com/cssref/css3_pr_opacity.asp
I'm not sure why you would want a percent instead of this number considering they are the same thing (just divide by 100).
Upvotes: 0