小编典典

使用CSS在背景图片上设置尺寸?

css

是否可以使用CSS设置背景图片的大小?

我想做类似的事情:

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

但是这样做似乎是完全错误的…


阅读 377

收藏
2020-05-16

共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;
}

特别是,我喜欢covercontain赋予我们前所未有的控制权的价值。

回合

您还可以background-size: round结合使用具有重复含义的含义:

.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;
}

这将调整图像宽度,使其适合背景定位区域中的所有次数。


附加说明
如果您需要的大小是静态像素大小,则可以通过物理方式调整实际图像的大小。这既可以提高调整大小的质量(假设您的图像软件比浏览器做得更好),又可以在原始图像大于要显示的图像时节省带宽。

2020-05-16