backgroundプロパティは、背景に関するスタイルをまとめて指定できるプロパティです。
背景に関するプロパティを使用すると、要素の背景に色や画像を表示させるだけでなく、ある画像をリピートして配置したり、色をグラデーションさせて表示したりと、さまざまな背景を作り出すこともできます。
今回は、このような背景に関するプロパティの種類と、使用頻度の高いbackground-colorプロパティについてまとめたいと思います。
背景に関するプロパティについては、以下のページもご参照下さい。
CSS【 background 】1~背景プロパティの種類とbackground-color(本ページ)
CSS【 background 】2~background-imageでレイヤーやグラデーションも
CSS【 background 】3~background-repeat、background-attachment
CSS【 background 】4~background-position
CSS【 background 】5~background-size
CSS【 background 】6~background-clip、background-origin
CSS【 background 】7~背景に関するショートハンドプロパティ
なお、未経験からITエンジニアへの就職に興味がある方や未経験からプログラミングを効率よく学びたいと考えている方は、就職率98.3%で受講料無料のプログラミングスクールプログラマカレッジもおすすめです。
背景に関するプロパティには、次のようなものがあります。
background-color | 背景の色を指定する
値:CSSの色指定(カラーネーム、RGB(16進数,10進数)、HSL)、キーワード transparent(透明)、currentColor(文字色) |
---|---|
background-image | 背景画像を指定する
値:url(“画像のURL”)、none |
background-repeat | 画像の繰り返し方法を指定する
値:repeat-x, repeat-y, repeat, no-repeat, space, round |
background-attachment | スクロール時の背景画像の動きを指定する
値:fixed, scroll, local |
background-position | 画像の表示位置を指定する
値:数値(pxやemなどの単位を付けて)、%、top、right、bottom、left、center |
background-size | 画像の表示サイズを指定する
値:数値(pxやemなどの単位を付けて)、%、auto、contain、cover |
background-clip | 背景の範囲を指定する
値:border-box、padding-box、content-box |
background-origin | 画像配置の基準位置を指定する
値:border-box、padding-box、content-box |
background | 背景に関するショートハンドプロパティ
値を半角スペースで区切って指定する |
background-colorプロパティは、要素の背景色を指定するプロパティです。
指定する値には次のようなものがあります。
CSSの色指定 | カラーネーム、RGB(16進数、10進数)、HSLなどのCSSの色指定 |
---|---|
transparent | デフォルト値 透明で、rgba(0,0,0,0)と同じ |
currentColor | 文字色(colorプロパティで指定された色)と同色 |
background-colorプロパティの値は、継承されません。
また、background-colorプロパティは、全ての要素で使用できます。
テキストに背景色を指定すると、次のような表示になります。
背景色:#993366
背景色:lightblue;
背景色:rgba(156,100,210,0.5)
背景色:hsla(181, 100%, 45%, 0.2)
背景色:transparent
背景色:currentColor
ソースは次の通りです。
<!-- CSSファイル -->
div#sample {margin:0;}
div#sample p {margin:1em 0; padding:0.3em 1em; background-color:#993366;}
div#sample p:nth-child(2) {background-color:lightblue;}
div#sample p:nth-child(3) {background-color:rgba(156,100,210,0.5);}
div#sample p:nth-child(4) {background-color:hsla(181, 100%, 45%, 0.2);}
div#sample p:nth-child(5) {background-color:transparent;}
div#sample p:nth-child(6) {background-color:currentColor;}
<!-- HTMLファイル -->
<div id="sample">
<p>背景色:#993366</p>
<p>背景色:lightblue;</p>
<p>背景色:rgba(156,100,210,0.5)</p>
<p>背景色:hsla(181, 100%, 45%, 0.2)</p>
<p>背景色:transparent</p>
<p><font color="#FFF">背景色:currentColor</font></p>
</div>
最後に指定したcurrentColorは、その要素の文字色(ここでは黒)と同色になるため、本来テキストの文字は背景色に紛れて読めませんが、HTMLのタグ内に別のフォントカラー(白)を設定しているので、文字が判別できています。
p:nth-child(N)というセレクタは、N番目のp要素をセレクタにするという擬似クラスです。
INTERNOUS,inc. All rights reserved.