可以用CSS设置背景图片的大小吗?

我想做一些类似的事情:

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

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

推荐答案

CSS2

如果需要将图像放大,则必须在图像编辑器中编辑图像本身.

如果你使用img标签,你可以改变大小,但是如果你需要图像作为其他内容的背景(并且它不会像你看起来想要的那样重复),那就不会给你想要的结果...

CSS3 unleash the powers

这可以在CSS3中使用background-size.

All modern browsers support this, so unless you need to support old browsers, this is the way to do it.
Supported browsers:
Mozilla Firefox 4.0+ (Gecko 2.0+), Microsoft Internet Explorer 9.0+, Opera 10.0+, Safari 4.1+ (webkit 532) and 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,它与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;
}

这将调整图像宽度,使其在背景定位区域中多次匹配.


Additional note
If the size you need is static pixel size, it is still smart to physically resize the actual image. This is both to improve quality of the resize (given that your image software does a better job than the browsers), and to save bandwidth if the original image is larger than what to display.

Css相关问答推荐

使用location:stickly将元素固定到其父容器的顶部

如何在CSS calc()中使用反向百分比/无单位计算?

转换间隙值时基于百分比的弹性元素&跳转

如何以Angular 将下拉面板的宽度与其文本框对齐

为什么CSS flex似乎应用了两次内部元素的填充?

Vuetify 抽屉标签溢出/z-index

使用 place-content: center 的全宽 CSS 网格项目

使 MUI 自动完成打断长词以适合布局

在 React 中使用 CSS 动画 onClick()

semantic-ui-react 使输入使用全宽度可用

如何给三角形添加渐变?

和号 (&) 作为 SASS @mixin 中的变量

CSS动画移动divs upwords

CSS Slanding Div 边缘在图像上

Bootstrap 类似乎没有任何作用

仅对父容器应用模糊效果

  • 元素上的子弹来自哪里?
  • 将未知大小的大图像居中在一个较小的 div 中,并隐藏溢出

    表格溢出时水平滚动

    :before 和 ::before 有什么区别?