背景图像缩放同时保持纵横比
我希望背景图像能够像幻灯片放映一样自动变化。但我希望图像填充背景,无论浏览器窗口的大小如何......并且如果缩小,图像的长宽比不会改变。
这是我正在尝试执行的操作的示例:
如何我能完成这些任务吗?任何帮助将不胜感激。
I would like to have images for my background that change automatically like a slide show. But I would like the images to fill the background no matter what size the browser window is...and if it is scaled down, the aspect ratio of the image does not change.
Here is an example of what I'm trying to do:
How can I accomplish these tasks? Any help will be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你不能,至少不能像你现在尝试的那样。
但是,您可以做的是创建一个
,并使用 css 设置
position:absolute
,将其缩放到 100% 宽度并从父级裁剪它以overflow:hidden
为例:http://jsfiddle.net/GHmz7/4/< /a>
You can't, at least not like you are trying to now.
What you can do, however, is create an
<img>
instead, and with css setposition:absolute
, scale it to 100% width and crop it from the parent withoverflow:hidden
example: http://jsfiddle.net/GHmz7/4/
您可以尝试 jquery/js 更改背景图像:
您可以为背景创建 CSS 类,并使用 .toggleClass()
You could try jquery/js to change the background image:
You can create CSS classes for the backgrounds instead, and use .toggleClass()
您无法在所有浏览器/版本等中可靠地调整背景图像的大小...
您在 thesixtyone.com 网站上看到的效果是通过将普通内联图像拉伸到其容器(即占位符划分)的 100% 来实现的。然后其他元素漂浮在这个“背景”部分的顶部。
所以答案不是使用背景图像,而是让图像在占位符中填充屏幕,然后将其他元素放在其上面。
You can not reliably resize background images across all browsers/versions etc...
The effect you see on thesixtyone.com site is achieved by stretching a normal inline image to 100% of it's container which is a placeholder division. Other elements are then floated over the top of this 'background' division.
So the answer is not to use a background image, but to make an image fill the screen in a placeholder, then put other elements on top of it.
对于 CSS3,您可以使用
background-size
属性。背景大小:包含;
将图像缩放到最大尺寸,同时保留其固有的纵横比(如果有),使其宽度和高度都能适合背景定位区域。
Contain
始终适合视口内的整个图像,只要背景图像和浏览器窗口的比例不同,就会在上下或左右留下不透明边框。背景大小:封面;
将图像缩放到最小尺寸,同时保留其固有的纵横比(如果有),使其宽度和高度都可以完全覆盖背景定位区域。
Cover
总是填充浏览器窗口,在此过程中剪掉一些头发或耳朵,这是我个人在大多数情况下更喜欢的。您可以使用背景位置属性控制图像在视口中的对齐方式。With CSS3, you would use
background-size
property.background-size: contain;
Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area.
Contain
always fits the entire image within your viewport, leaving opaque borders on either the top-bottom or the left-right whenever the ratio of the background image and browser window are not the same.background-size: cover;
Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.
Cover
always fills the browser window, cutting off some hair or ears in the process, which is what I personally prefer for most cases. You can control how your image is aligned within the viewport by using the background-position property.