5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[CSS] opacity で困った

Last updated at Posted at 2022-04-15

opacity で困った!

  • Vue.js + tailwind 環境
  • ローディングのオーバーレイを CSS のプロパティ opacity で実装した。
  • Firefox ではうまくレンダリングされたが、chrome で表示が崩れた。
  • しかも2回目以降のローディング表示は正しく表示された。

1 回目 → 崩れる

image.png

2 回目 → 正しく表示される

image.png

opacity vs rgba

opacity の挙動が怪しいと思ったので調べました。

opacity

子要素の textbackground の不透明度をすべて変更する

rgba

スタイルを指定した要素のみに不透明度を設定する

デモ

rgba を使用した container では、子要素に影響を与えないが、opacity を使用した container-opacity は子要素の backgroundtext に不透明度が設定されている。

See the Pen Untitled by shiraishi yuma (@punkshiraishi) on CodePen.

rgba に変更した結果

1回目から崩れずに表示されるようになりました。
image.png

仮説

opacity 属性による指定では、より多くの要素をレンダリングすることになる。Vue による DOM の生成のタイミングなどの条件と重なり、表示崩れを起こしてしまった。

一方 rgba では単一の要素にしか影響を与えないので、レンダリング処理がシンプルになり、問題が解消したのではないか。

tailwind を使う場合

opacity-xx

opacity: xx; を付与します。

bg-opacity / text-opacity / border-opacity

rgba で不透明度を指定します。

bg-red-500 は下記のようなスタイルが付与されます。

.bg-red-500 {
    --tw-bg-opacity: 1;
    background-color: rgba(185,28,28,var(--tw-bg-opacity));
}

--tw-bg-opacity は変数で、bg-opacity によって指定できます。

.bg-opacity-50 {
  --tw-bg-opacity: 0.5;
}

結論

opacity は影響範囲を理解して使いましょう。
特定の要素の不透明度を変えたいときはなるべく rgba を使った方が良さそうです。

参考

5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?