background-repeatプロパティは、背景画像を繰り返して表示するかどうか、またどの方向に繰り返すかを制御するためのプロパティです。背景画像が要素のサイズより小さい場合に使用されます。
background-repeatプロパティの値とその効果
repeat: 背景画像を水平方向および垂直方向に繰り返して表示します(デフォルト値)。repeat-x: 背景画像を水平方向のみに繰り返して表示します。repeat-y: 背景画像を垂直方向のみに繰り返して表示します。no-repeat: 背景画像を繰り返さずに1回だけ表示します。
注意点と関連情報
background-repeatプロパティを使うと、背景画像を要素全体に渡って繰り返すか、特定の方向に繰り返すかを選択できます。また、background-sizeプロパティと組み合わせると、繰り返し画像のサイズを調整することができます。要素が大きすぎて背景が足りない場合や、逆に背景が小さすぎて繰り返し表示が多くなる場合などに便利です。
background-repeatプロパティが効かない時の原因と対策
背景画像が指定されていない
background-repeatは背景画像に対して適用されるプロパティです。背景画像が指定されていない場合、background-repeatの効果は確認できません。
対策: background-imageで背景画像を指定し、background-repeatの効果が適用されるようにしてください。
共通するCSSコード
.css-sample-container {
width: 100%;
max-width: 600px;
padding: 20px;
margin: 50px auto;
border: 1px solid #000;
text-align: center;
font-size: 18px;
color: #333;
box-sizing: border-box;
background-image: url('https://programming-cafe.com/wp-content/uploads/colorphoto02.jpg');
background-size: 100px 100px;
height: 300px;
}
background-repeat: repeat
background-repeat: repeatは、背景画像を水平方向と垂直方向に繰り返して表示します。これがデフォルトの設定です。
HTMLコード
<div class="css-sample-container css-sample-repeat">
背景画像が水平方向と垂直方向に繰り返して表示されます。
</div>
CSSコード
.css-sample-repeat {
background-repeat: repeat;
}
表示結果
background-repeat: repeat-x
background-repeat: repeat-xは、背景画像を水平方向のみに繰り返して表示します。
HTMLコード
<div class="css-sample-container css-sample-repeat-x">
背景画像が水平方向のみに繰り返して表示されます。
</div>
CSSコード
.css-sample-repeat-x {
background-repeat: repeat-x;
}
表示結果
background-repeat: repeat-y
background-repeat: repeat-yは、背景画像を垂直方向のみに繰り返して表示します。
HTMLコード
<div class="css-sample-container css-sample-repeat-y">
背景画像が垂直方向のみに繰り返して表示されます。
</div>
CSSコード
.css-sample-repeat-y {
background-repeat: repeat-y;
}
表示結果
background-repeat: no-repeat
background-repeat: no-repeatは、背景画像を繰り返さずに1回だけ表示します。画像が要素のサイズより小さい場合、残りの部分は背景色が適用されます。
HTMLコード
<div class="css-sample-container css-sample-no-repeat">
背景画像が1回だけ表示されます。
</div>
CSSコード
.css-sample-no-repeat {
background-repeat: no-repeat;
}
表示結果
まとめ
background-repeatプロパティは、背景画像を繰り返し表示するか、どの方向に繰り返すかを制御する重要なプロパティです。水平方向や垂直方向に繰り返すか、繰り返しなしに1回だけ表示するかなど、要素のレイアウトやデザインに応じて調整できます。他のbackground関連プロパティと組み合わせることで、さらに柔軟なデザインが可能になります。