简体   繁体   English

如何使CSS中的背景图像响应

[英]How to make a background image responsive in CSS

I asked a question previously on getting 2 divs to sit inside another div bootstrap container (1 top left, and 1 bottom right) which has now been solved. 之前我问了一个问题,就是让2个div进入另一个div bootstrap容器(1个左上角,1个右下角),现在已经解决了。

My next issue is, in the main div (with 2 divs sitting inside) I need a large background image, which is responsive, so brings the bottom right div upwards and inwards as the browser is made smaller. 我的下一个问题是,在主div(里面有2个div)我需要一个大的背景图像,它是响应的,所以当浏览器变小时,将右下角div向上和向内。

Here is what I have so far: 这是我到目前为止:

<style>
#header {
background-image: url(/images/background-image.jpg);
position: relative;
}

#header .container {
height: 893px;
position: relative;
}

#header .div1 {
position: absolute;
top: 20px;
}

#header .div2 {
position: absolute;
bottom: 20px;
right: 20px;
}

<div id="header">
<div class="container">
    <div class="div1">
        Top left content
    </div>
    <div class="div2">
        Bottom right content
    </div>
</div>

Adding the background image to the CSS like how I have done above, does not make the image responsive, but if I add it to the HTML as an image I cannot get the divs to sit on top of the image. 像我上面所做的那样将背景图像添加到CSS中,不会使图像响应,但如果我将其作为图像添加到HTML中,则无法让div位于图像的顶部。

What is the correct method of doing this? 这样做的正确方法是什么?

With a few cross-browser vendor prefixes. 有一些跨浏览器的供应商前缀。

#header {
    display: block;
    position: relative;
    background: url('/images/background-image.jpg') 50% 0 no-repeat;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

This may solve or at least get you in the right direction. 这可能会解决或至少让您朝着正确的方向前进。 Change you header styles to the following and it will force the background image to the top left and fill 100% of the div. 将标题样式更改为以下内容,它将强制将背景图像放在左上角并填充100%的div。 It can be tricky to have "perfectly" responsive background images. 拥有“完美”响应背景图像可能会很棘手。

#header {
background-image: url(/images/background-image.jpg);
background-repeat:no-repeat;
background-size: 100%;
background-position:top left;
position: relative;
}

http://codepen.io/adamfollett/pen/OXdKyG http://codepen.io/adamfollett/pen/OXdKyG

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM