CSS 即使调整窗口大小,也保持背景图像居中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6272172/
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
Keep a background image centered even when window is resized
提问by Calvin
I have a container div with another div centered inside with a background image.
我有一个容器 div,其中另一个 div 以背景图像为中心。
When I resize the browser window, I want the image to stay centered, even when the width of the browser window is smallerthan the width of the image.
当我调整浏览器窗口的大小时,我希望图像保持居中,即使浏览器窗口的宽度小于图像的宽度。
Here's some code:
这是一些代码:
CSS:
CSS:
.wrap {
width:100%;
height:357px;
background-color:red;
overflow:hidden;
text-align:center;
}
.image {
margin:0 auto;
background:url('http://4.bp.blogspot.com/-GKx0A_H8DGE/Tb9bTBCC5pI/AAAAAAAAANc/jvjcjvuNmGk/s1600/wide-angle-lens-3-1.jpg') no-repeat;
width:500px;
height:357px;
}
HTML:
HTML:
<div class="wrap">
<div class="image"></div>
</div>
You can see that when the browser is resized, the image stops "centering" itself after it hits the left side of the screen. What I'd like is to still see the center of the image, with the left side getting clipped off and essentially moving off-screen to the left. Is this possible with just CSS? I'd also be interested in a JS solution if not possible.
您可以看到,当浏览器调整大小时,图像在到达屏幕左侧后停止“居中”。我想要的是仍然看到图像的中心,左侧被剪掉并基本上向左移出屏幕。这可能只用 CSS 吗?如果不可能,我也会对 JS 解决方案感兴趣。
回答by NGLN
.wrap {
height: 357px;
background-color: red;
overflow: hidden;
position: relative;
}
.image {
position: absolute;
left: 50%;
margin-left: -250px;
background:url('/image.jpg') no-repeat;
width:500px;
height:357px;
}