CSS
 Computer >> コンピューター >  >> プログラミング >> CSS

CSSのbackgroundプロパティとは?背景設定を一括指定する方法を実例付きで解説

CSSのbackgroundプロパティは、背景色・背景画像・繰り返し方法・スクロール時の挙動・表示位置など、背景に関するすべての設定を1つの宣言でまとめて指定できるショートハンド(省略記法)プロパティです。

個別にbackground-colorbackground-imageなどを分けて記述する必要がないため、コードが簡潔になり、可読性も向上します。

backgroundプロパティで指定できる主な値

  • background-color:背景色(例:lightblue)
  • background-image:背景画像のURL(例:url("image.jpg"))
  • background-repeat:画像の繰り返し方法(no-repeat は繰り返しなし)
  • background-attachment:スクロール時の挙動(fixed は画面に固定)
  • background-position:画像の表示位置(top は上部中央)

実装サンプル

以下のコードでは、薄い水色(lightblue)の背景色にロゴ画像を重ね合わせ、「繰り返しなし・画面に固定・上部に配置」という条件を一括で指定しています。実際にブラウザで実行して動作を確認してみましょう。

<html>
   <head>

      <style>
         #demo {
            background: lightblue url("https://www.tutorialspoint.com/css/images/css-mini-logo.jpg") no-repeat fixed top;
         }
      </style>

   </head>
   <body>
      <div id="demo">
         <h1>www.tutorialspoint.com</h1>
         <p>Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at
            their own pace from the comforts of their drawing rooms. The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated,
            we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of tutorials and allied articles on
            topics ranging from programming languages to web designing to academics and much more..</p>
      </div>
   </body>

</html>

まとめ

backgroundプロパティを使いこなせば、複数行にわたる背景スタイルの指定を1行に集約できます。値の順序は厳密には決まっていませんが、「色 → 画像 → 繰り返し → 固定 → 位置」の順で記述すると読みやすくなります。Webページのデザイン性を高める第一歩として、ぜひ活用してください。

  1. CSSのuser-selectプロパティとは?テキスト選択を制御する方法と実例

    CSSの user-select プロパティを使うと、要素内のテキストがユーザーによって選択可能かどうかを制御できます。たとえば、ボタンのラベルやナビゲーションメニューなど、誤って選択されたくないテキストに対して「選択不可」に設定することで、より快適なユーザー体験を提供できます。 user-selectプロパティの主な値 none … テキストを選択できなくします auto … ブラウザの既定動作に従います(初期値) text … テキストを選択可能にします all … 要素をクリックすると、その内容全体が選択されます 使用例 次の例では、<div> 要素内のテキストに use

  2. CSSのbackgroundショートハンド(一括指定)プロパティの使い方を解説

    CSSのbackgroundショートハンド(一括指定)プロパティは、要素の背景をまとめて定義するための便利なプロパティです。1つの宣言で複数の背景関連プロパティを同時に設定できるため、コードが簡潔になり、可読性も向上します。backgroundショートハンドに含まれる個別プロパティbackgroundショートハンドを使うことで、以下の8つの個別プロパティを一度に指定できます。background-color:背景色background-image:背景画像background-repeat:画像の繰り返し方法background-position:画像の表示位置background-clip: