Html 在 CSS 中水平调整页面大小时如何停止图像缩小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10655181/
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
How to stop image shrinking when page is resized horizontally in CSS
提问by Hyman Greenhill
I have a 1920x100 image which is inserted at the top of my page:
我有一个 1920x100 的图像,它被插入到我的页面顶部:
<img src="./Resources/Images/banner.jpeg" style="position:absolute; top:0px; left:0px; height:100px; width:100%;" name="top">
I'd like to have it so that when the page is resized horizontally, the image doesn't shrink with the page, but instead remains in the center of the screen, like this:
我想要这样,当页面水平调整大小时,图像不会随着页面缩小,而是保留在屏幕中央,如下所示:
It seems like a simple thing that could be easily achieved, but I haven't found a solution.
这似乎是一件很容易实现的简单事情,但我还没有找到解决方案。
I could put the image inside a div and set the left position of the div to be -(1920-pageWidth) / 2, but this would rely on JavaScript. I'm looking for a cleaner solution (if there is one), just to minimize complexity on the page, and maximize browser compatibility.
我可以将图像放在 div 中并将 div 的左侧位置设置为 -(1920-pageWidth) / 2,但这将依赖于 JavaScript。我正在寻找一种更简洁的解决方案(如果有的话),只是为了最大限度地减少页面的复杂性,并最大限度地提高浏览器的兼容性。
Is there any CSS property I could use to achieve this, or am I going the completely wrong way of achieving this?
是否有任何 CSS 属性可以用来实现这一点,或者我是否采用了完全错误的方式来实现这一点?
Any help appreciated.
任何帮助表示赞赏。
采纳答案by yunzen
With CSS
使用 CSS
div {
background: url(./Resources/Images/banner.jpeg) no-repeat scroll center top transparent;
height: 100px;
}
回答by gabitzish
You can add this css property to your image : min-width: 1280px
您可以将此 css 属性添加到您的图像中: min-width: 1280px
回答by Tom Pietrosanti
What about something like this. (use half the image width for the margin-left
)
这样的事情怎么办。(使用图像宽度的一半作为margin-left
)
HTML:
HTML:
<div id='wrapper'>
<img src='./Resources/Images/banner.jpeg' id='banner'>
</div>
CSS:
CSS:
#wrapper{overflow:hidden;position:relative;}
#banner{position:absolute;top:0;left:50%;margin-left:-960px;}
Here's a fiddle demonstrating it using a div (change the width of #wrapper
):
http://jsfiddle.net/mestekweb/mDkrE/
这是一个使用 div 演示它的小提琴(更改 的宽度#wrapper
):http:
//jsfiddle.net/mestekweb/mDkrE/
回答by GodLesZ
回答by Litek
Instead of using img
element use the same image as background-image, and position in to center. It will always be centered, but may be clipped when the element is smaller then the image. You should also set background-repeat to no-repeat in case the element gets bigger.
而不是使用img
元素使用与背景图像相同的图像,并将其定位到中心。它始终居中,但当元素小于图像时可能会被剪裁。您还应该将 background-repeat 设置为 no-repeat 以防元素变大。
div {
background: url(/to/img) no-repeat 50% 0;
margin: 0 auto;
}