使用 CSS 使图像放大和缩小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/821399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use CSS to make an image scale up and down
提问by seanmonstar
I have an image in the header of my website. I'd like to use a CSS property to make it stretch across the width of the browser, so that it reacts to the user adjusting the browser window size, and so that the vertical axis of the image is scaled accordingly. Is this actually something that can be done?
我的网站标题中有一张图片。我想使用 CSS 属性使其在浏览器的宽度上拉伸,以便它对用户调整浏览器窗口大小做出反应,并相应地缩放图像的垂直轴。这真的是可以做到的吗?
回答by seanmonstar
Percentages will keep an image the whole width, and will update the image on browser resizing.
百分比将使图像保持整个宽度,并将在浏览器调整大小时更新图像。
If you want the image to alwaysbe stretch, you can use:
如果您希望图像始终被拉伸,您可以使用:
img {
width:100%;
}
However, that can easily make the image look like total crap. A safer way might be:
但是,这很容易使图像看起来完全是废话。更安全的方法可能是:
img {
max-width:100%;
}
Either way will get the image changing sizes with browser resizing. However, the second won't stretch the image past it's natural size, so it doesn't look deformed.
无论哪种方式,都会通过浏览器调整大小来改变图像的大小。但是,第二个不会将图像拉伸超过其自然尺寸,因此它看起来不会变形。
回答by Thomas Owens
You can set the width and height properties to percentages (for example, a width of 100% would cause the image to stretch across your page). This can be done using CSS.
您可以将宽度和高度属性设置为百分比(例如,宽度为 100% 会导致图像在整个页面上拉伸)。这可以使用 CSS 来完成。
回答by David says reinstate Monica
CSS can certainly stretch an image (or, at least, I've used it to do so in Firefox at the folowing url: http://www.davidrhysthomas.co.uk/mindez/borked.html):
CSS 当然可以拉伸图像(或者,至少,我已经在 Firefox 中使用它在以下 url 中执行此操作: http://www.davidrhysthomas.co.uk/mindez/borked.html):
img {height: 100%;
width: 100%;
min-height: 600px;
min-width: 800px;
}
for example.
例如。
But...I think for it to react to the viewport resizing that JS would be probably your better-friend.
但是......我认为它对调整视口大小做出反应,JS可能是你的好朋友。
回答by Toby
Here, give this a go, just apply this CSS style to the element that contains the image. In this example the image is on the background of the page body:
在这里,试一试,只需将此 CSS 样式应用于包含图像的元素即可。在此示例中,图像位于页面正文的背景上:
body
{
margin: 0;
padding: 0;
width: 100%;
background: url(images/YOUR-IMAGE.JPG) no-repeat left top;
background-size: 100%;
}
This will maximise your image across the element. Resizing the window will scale the image to fit the browsers new window size
这将使您在整个元素上的图像最大化。调整窗口大小将缩放图像以适应浏览器的新窗口大小