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

的CSS CSS

老丝番长

2020-03-20

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

我想做类似的事情:

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

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

第2425篇《使用CSS在背景图片上设置尺寸?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

10个回答
Harry逆天Eva 2020.03.20

If you want to set background-size in the same background property you can use use:

background:url(my-bg.png) no-repeat top center / 50px 50px;
宝儿米亚飞云 2020.03.20

I use background images for buttons, but it only shows the image the same size as the text, even if I set width and height. Instead, I pad out my text with   characters (non-breaking spaces). I slap in as many as needed, basically, until all the button background appears. So I might have code like this:

In the style sheet:

#v2menu-home {
    background-image:url(../v2-siteimages/button.png);
    background-repeat:no-repeat;
}

In the HTML document:

<div id="v2menu">
    <a id="v2menu-home" href="/index.php">home&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>
</div><!-- v2menu -->
伽罗Gil 2020.03.20

background-size 可以在Chrome 4.1中使用,但到目前为止我无法在Firefox 3.6中使用。

老丝Stafan 2020.03.20

您可以使用两个<div>元素:

  • 一个是容器(它是您最初希望背景图像显示在其中的容器)。

  • 第二个包含在其中。您可以将其大小设置为背景图像的大小(或希望显示的大小)。

然后将包含的div设置为position absolute这样,它不会干扰包含div中项目的正常流动。

它使您可以有效使用精灵图像。

斯丁小胖Jim 2020.03.20

您无法使用当前版本的CSS(2.1)设置背景图片的大小。

您只能设置:positionfiximage-urlrepeat-mode,和color

泡芙神奇 2020.03.20

您完全可以使用CSS3:

body {
    background-image: url(images/bg-body.png); 
    background-size: 100%; /* size the background image at 100% like any responsive img tag */
    background-position: top center;
    background-repeat:no-repeat;
 }

这会将背景图像的大小调整为body元素宽度的100%,然后随着body元素的大小调整为较小的分辨率而相应地重新调整背景的大小。

这是示例:http : //www.sccc.premiumdw.com/examples/resize-background-images-with-css/

老丝乐 2020.03.20

如果您的用户仅使用Opera 9.5 +,Safari 3 +,Internet Explorer 9+和Firefox 3.6+,那么答案是肯定的。否则,不会。

背景大小的属性是CSS 3的一部分,但它不会工作在大多数浏览器。

为了您的目的,请放大实际图像。

猿前端 2020.03.20

只有CSS 3支持该功能,

background-size: 200px 50px;

但是我会编辑图像本身,以便用户需要减少加载,并且它看起来比没有抗锯齿功能的缩小图像更好。

理查德Green 2020.03.20

如果您不害怕更深入一点,那就不太难了:)

有一个被遗忘的论点:

background-size: contain;

这不会像拉伸background-image那样伸展您的身体cover它会一直延伸到较长的一侧达到外部容器的宽度或高度,从而保留图像。

编辑:还有-webkit-background-size-moz-background-size

在IE9 +,Firefox 4 +,Opera,Chrome和Safari 5+中支持background-size属性。

-资料来源:W3学校

凯老丝 2020.03.20

background-size:200px 50px将其更改为100%100%,它将根据诸如ul li或div之类的内容标签的需要进行缩放。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android