开发者

Keep a background image centered even when window is resized

开发者 https://www.devze.com 2023-03-11 07:44 出处:网络
I have a container div with another div centered inside with a background image. When I resize the browser window, I want the image to stay centered, even when the width of the browser window is sma

I have a container div with another div centered inside with a background image.

When I resize the browser window, I want the image to stay centered, even when the width of the browser window is smaller than the width of the image.

Here's some code:

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:

<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 of开发者_开发问答f 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.


.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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消