The opacity value was changed to 1% after building the Reacjs project

ReactjsNode Sass

Reactjs Problem Overview


Im building a Reactjs project and using scss instead of css. In the App.scss file, I set opacity: 87%; (note: unit is percent).

Everything worked normally (the opacity value still equal 87%) when I run command: yarn start

But when I run command: yarn build and check value opacity in the file build/static/css/main.86352307.chunk.css then the opacity value was changed to 1%.

File App.scss:

.App {
  text-align: center;
  opacity: 87%;
}

After build project: File build/static/css/main.86352307.chunk.css

.App{text-align:center;opacity:1%}
/*# sourceMappingURL=main.86352307.chunk.css.map */

Step to reproduce issue

#1. npx create-react-app my-app
#2. cd my-app
#3. yarn add node-sass
#4. rename file App.css to App.scss and then add opacity: 87% in class .App

#Testcase 1: run yarn start => the opacity value (87%) is apply for class .App
#Testcase 2: run yarn build => the opacity value (1%) is apply for class .App

Please tell me know the reason.

Reactjs Solutions


Solution 1 - Reactjs

This issue has been reported in create-react-app and optimize-css-assets-webpack-plugin.

https://github.com/facebook/create-react-app/issues/7980

https://github.com/NMFR/optimize-css-assets-webpack-plugin/issues/118

It appears the bug has been fixed, but the latest released version does not have the fix. I've fixed the problem by changing my opacity values from nn% to 0.nn values (e.g. 70% becomes 0.7).

Solution 2 - Reactjs

I think opacity accepts values in the range 0.0 to 1.0. Any value outside the interval, though valid, is clamped to the nearest limit in the range. In your example the nearest limit is clamped to 1%;

https://developer.mozilla.org/en-US/docs/Web/CSS/opacity

Solution 3 - Reactjs

On production build the css optimiser (cssnano) is rounding up the number(87 in your case). This is happening in angular version 9 and up also.

To avoid this, you can use the values between 0 and 1. In your case, you can use 0.8 as below inside your css rule

opacity: 0.8;

MDN guild on opacity

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHo VanView Question on Stackoverflow
Solution 1 - ReactjsScott DanielView Answer on Stackoverflow
Solution 2 - ReactjsSai ChandraView Answer on Stackoverflow
Solution 3 - ReactjsAnand RajaView Answer on Stackoverflow