本記事では、CSSで要素を透明・半透明にする方法について解説しています。
ITエンジニア特化の転職サイト!
自社内開発求人に強い【クラウドリンク】
HTML/CSSの学習におすすめ参考書
1冊ですべて身につくHTML&CSSとWebデザイン入門講座
Contents
要素を透明・半透明にする
要素を透明・半透明にするにはopacityプロパティを使用します。
opacity: 0~1;
opacityプロパティに設定できる値は0〜1の数値です。0は完全なる透明を表し、1は完全なる不透明を表します。つまり、0に近い値を設定すれば要素は透明に近い半透明になり、1に近い値を設定すれば要素は不透明に近い半透明になります。
<div class="wrapper">
<div class="content0">opacity:0</div>
<div class="content1">opacity:0.1</div>
<div class="content2">opacity:0.2</div>
<div class="content3">opacity:0.3</div>
<div class="content4">opacity:0.4</div>
<div class="content5">opacity:0.5</div>
<div class="content6">opacity:0.6</div>
<div class="content7">opacity:0.7</div>
<div class="content8">opacity:0.8</div>
<div class="content9">opacity:0.9</div>
<div class="content10">opacity:1</div>
</div>
div.wrapper{
display:flex;
flex-wrap:wrap;
}
div:not(.wrapper){
display:flex;
align-items:center;
justify-content:center;
width:150px;
height:100px;
background:skyblue;
}
.content0{
opacity:0;
}
.content1{
opacity:0.1 ;
}
.content2{
opacity:0.2;
}
.content3{
opacity:0.3;
}
.content4{
opacity:0.4;
}
.content5{
opacity:0.5;
}
.content6{
opacity:0.6;
}
.content7{
opacity:0.7;
}
.content8{
opacity:0.8;
}
.content9{
opacity:0.9;
}
.content10{
opacity:1;
}
opacityの注意点
opacityを使う上での注意点として、opacity:0で完全に要素を透明にしても要素の幅と高さは確保されている状態になります。
分かりやすいように下記のサンプルコードを実行して、表示を確認してみましょう。
<div class="item01">要素1</div>
<div class="item02">要素1</div>
<div class="item03">要素1</div>
div{
width:100px;
height:100px;
display:flex;
align-items:center;
justify-content:center;
}
.item01{
background:#f00;
}
.item02{
background:#0f0;
opacity:0;
}
.item03{
background:#00f;
}
3つの要素にそれぞれ幅と高さに100pxを設定し、真ん中の要素にだけopacity:0を設定し完全に要素を透明にしています。
このコードの表示結果を確認すると
1つ目と3つ目の要素の間に大きな余白が空いています。実はこれopacity:0を設定した2つ目の要素が透明だけど幅と高さが確保しているため、このような表示になっています。