CSSのbackgroundプロパティで背景画像の各種設定を1行でまとめて指定する方法
CSSのbackgroundプロパティを使うと、背景色・背景画像・繰り返し方法・スクロールの有無・表示位置など、背景に関するすべてのプロパティを1つの宣言にまとめて設定できます。
個別にbackground-colorやbackground-imageなどを指定する代わりに、この一括指定(ショートハンド)プロパティを利用することで、コードがすっきりし、スタイルの管理も容易になります。
指定できる主な値
- background-color … 背景色(例:lightblue)
- background-image … 背景画像のURL(例:url("sample.jpg"))
- background-repeat … 画像の繰り返し方法(例:no-repeat)
- background-attachment … スクロール時の挙動(例:fixed)
- background-position … 画像の表示位置(例:top)
サンプルコード
以下のコードを実行すると、backgroundプロパティによる一括指定の動作を確認できます。
<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>この例では、#demo要素に対して水色(lightblue)の背景色とロゴ画像を同時に指定しています。画像は繰り返しなし(no-repeat)、スクロールしても固定され(fixed)、上部(top)に配置されます。
-
CSSのborder-radiusプロパティで4つの角丸をまとめて設定する方法
CSSの border-radius プロパティを使用すると、要素の4つの角(左上・右上・右下・左下)の丸みを、たった1行のコードでまとめて設定できます。個別に指定する手間が省け、角丸デザインを効率的に実装できる便利なショートハンドプロパティです。border-radiusの基本的な使い方以下のサンプルコードでは、border-radius: 25px; を指定することで、青い背景のボックスの四隅すべてに25pxの丸みを付けています。サンプルコード<html> <head> <style>
-
CSSで背景に放射状グラデーション(radial-gradient)を設定する方法
CSSのradial-gradient()関数を使用すると、中心点から外側に向かって色が変化する放射状グラデーションを、背景画像として簡単に設定できます。複数の色を指定するだけで、滑らかなグラデーションが自動的に生成されるため、ボタンやバナー、セクション背景などのデザインに幅広く活用できます。radial-gradient()の基本構文background: radial-gradient(色1, 色2, 色3, ...);色はカンマ区切りで複数指定でき、左側に記述した色が中心になり、右側の色が外周へと変化していきます。実装例次のコードでは、緑(green)・オレンジ(orange)・栗色(m