CSS で背景画像のサイズを設定するには?質問する

CSS で背景画像のサイズを設定するには?質問する

CSS で背景画像のサイズを設定することは可能ですか?

次のようなことをしたいです:

background: url('bg.gif') top repeat-y;
background-size: 490px;

しかし、どうやらそうするのは完全に間違っているようです...

ベストアンサー1

CSS2

画像を大きくする必要がある場合は、画像エディタで画像自体を編集する必要があります。

img タグを使用するとサイズを変更できますが、画像を他のコンテンツの背景にする必要がある場合は、望ましい結果は得られません (また、希望どおりに繰り返されません)...

CSS3のパワーを解き放つ

これは CSS3 で を使って実行できますbackground-size

すべての最新ブラウザはこれをサポートしているので、古いブラウザをサポートする必要がない限り、これが実行方法です。
サポートされているブラウザ:
Mozilla Firefox 4.0+ (Gecko 2.0+)、Microsoft Internet Explorer 9.0+、Opera 10.0+、Safari 4.1+ (webkit 532)、Chrome 3.0+。

.stretch{
/* Will stretch to specified width/height */
  background-size: 200px 150px;
}
.stretch-content{
/* Will stretch to width/height of element */
  background-size: 100% 100%;
}

.resize-width{
/* width: 150px, height: auto to retain aspect ratio */
  background-size: 150px Auto;
}
.resize-height{
/* height: 150px, width: auto to retain aspect ratio */
  background-size: Auto 150px;
}
.resize-fill-and-clip{ 
  /* Resize to fill and retain aspect ratio.
     Will cause clipping if aspect ratio of box is different from image. */ 
  background-size: cover;
}
.resize-best-fit{
/* Resize to best fit and retain aspect ratio.
   Will cause gap if aspect ratio of box is different from image. */ 
  background-size: contain;
}

特に、これまではなかった新たな制御力を与えてくれる と の値がcover気に入っています。contain

ラウンド

background-size: round「that have a meaning」を「repeat」と組み合わせて使用​​することもできます。

.resize-best-fit-in-repeat{
/* Resize to best fit in a whole number of times in x-direction */ 
  background-size: round auto; /* Height: auto is to keep aspect ratio */
  background-repeat: repeat;
}

これにより、画像の幅が調整され、背景配置領域に整数倍で収まるようになります。


追加メモ
必要なサイズが静的なピクセル サイズである場合、実際の画像を物理的にサイズ変更することが賢明です。これは、サイズ変更の品質を向上させるため (画像ソフトウェアがブラウザーよりも優れた処理をする場合)、および元の画像が表示するサイズよりも大きい場合に帯域幅を節約するためです。

おすすめ記事