How do I set the background image size in CSS?

2019-03-03 23:24发布

So I have css code as follows:

.jumbobg {
    background: url('http://znc.mane-frame.com/static/silverleaf.png') fixed no-repeat, url('../img/banner-1008444.jpg') no-repeat, grey;
}

I was wondering, for the first image (silverleaf.png) - how would I set the background-size for that particular image, using either pixels (for silverleaf) or auto? I tried with background-size tag, but it would resize all the backgrounds defined above.

3条回答
啃猪蹄的小仙女
2楼-- · 2019-03-04 00:11

The thing is that you have specified two backgrounds in background property (separated with comma), so you have to do the same with background-size to get their distinct values, when you specify only one value in background-size it is applied for both images, to be clear:

background-size: 50px 80px; - this is one value

background-size: 50px 80px, auto; - those are two values

Use comma separator as you did in background, so for example this should work as you want:

background-size: 50px 80px, auto;
查看更多
不美不萌又怎样
3楼-- · 2019-03-04 00:19

Try this:

background-image: url('http://znc.mane-frame.com/static/silverleaf.png'), url(../img/banner-1008444.jpg);
background-repeat: repeat, no-repeat;
background-position: 0 0;
background-size: 350px 350px, cover;
查看更多
叼着烟拽天下
4楼-- · 2019-03-04 00:22

for multiple backgrounds in the way you are using (shorthand) here is the syntax:

background: [ <bg-layer> , ]* <final-bg-layer>

<bg-layer> = <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2}

<final-bg-layer> = <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2} || <background-color>

so with that in mind here is an example how to set background-size for the 1st background:

body {
  background: url(http://lorempixel.com/1200/900) repeat-x scroll 0 45px / auto 100%, url(http://lorempixel.com/1200/45) no-repeat scroll center 0 / 100% auto
}

查看更多
登录 后发表回答