LoginSignup
54
54

More than 5 years have passed since last update.

backgroundまとめ。ショートハンド、複数指定、各プロパティ

Last updated at Posted at 2016-04-21

ショートハンドで指定できるプロパティ

プロパティ 初期値
background-color transparent
background-image none
background-repeat repeat
background-origin padding-box
background-position 0% 0%
background-size auto auto
background-attachment scroll
background-clip border-box

このうち、background-sizeについてはbackground-positionの指定の後に、'/'で区切って指定しなければならないため注意が必要。

background: #333 url('bg.png') no-repeat border-box left top/contain fixed content-box;

ブラウザ問題
このショートハンドはAndroid4.4以下ではうまく作動しないことを確認している。
原因は'/'で区切る部分なのでそれまではOKか。
ただし、Android4.4以下はbackground-positionのleft、topなどを指定してのオフセット表記、background-sizeのcontain、coverが効かないなど割りと問題児。
background-positionはleft、topを指定せずに記述、background-sizeは100% autoまたはauto 100%にするなど代替方法はあるが注意が必要。
CanIuse(css-background-offsets)

複数の背景設定

カンマ区切りで指定できるが、、、

background: url('bg.jpg') no-repeat left top, #444 url('bg2.jpg') no-repeat right bottom;

ショートハンドでも普通にカンマ区切りで指定できる。
ただし、background-colorについては最後のひとつに対してしか指定できないので注意が必要。
また、スマートフォンなどでは以下の不具合(仕様?)があるので注意。

backgroudの画像を複数指定するとうまく表示されない!?

画像を複数指定するとショートハンドではうまく表示されない場合があるので、プロパティごとに分けて記述する。

background-color: #444;
background-image: url('bg.jpg'), url('bg2.jpg');
background-repeat: no-repeat, no-repeat;
background-position: left top, right bottom;

忘れがちなbackgroundプロパティについて

background-origin、background-crip

originは背景画像の配置領域を決める。
cripは背景の配置領域そのものを決める
正直あまり使うことはない。

border-box

ボーダー領域から背景が描かれる。
ただし、ボーダーの奥に描かれる。

padding-box

ボーダー領域には背景が描かれない。
パディング領域から背景が描かれる。

content-box

パディング領域には背景が描かれない。

background-position

background-position: left 20% bottom 50px;

基本的に縦方向、横方向の2つの値を指定する。
top、bottom、left、right、centerで四隅または中央を指定できるほか、
それらに続けて相対値、絶対値でのオフセットを指定できる。
デフォルトでは0% 0%(正確にはtop 0% left 0%)。

background-size

100% 100%

背景配置領域の縦横の100%を背景画像に適用する。
背景画像の縦横比率は保たれない。
背景配置領域に空きはでない。

cover

背景配置領域の縦横の大きい方を基準に背景画像の縦横比率を保ったまま表示する。
つまり、背景画像は大きくなり領域をリサイズすれば画像ははみ出す場合がある。
背景配置領域に空きはでない。

contain

背景配置領域の縦横の小さい方を基準に背景画像の縦横比率を保ったまま表示する。
つまり、背景画像は小さくなり領域をリサイズしても画像がはみ出すことはない。
背景配置領域に空きがでる。

background-attachment

fixed

スクロールしても背景画像が固定されてついてくる。

参考URL

background - CSS | MDN

54
54
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
54
54