如何将图像调整为div的背景?

时间:2015-10-23 11:15:05

标签: html css image

我正在尝试在我要显示图片的页面上执行header。要执行header我使用div

<div id = "header">
</div>

我希望图片会显示在div的背景上,所以我放了CSS

#header{
    background-image: url('img/cars.jpg');
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: 100%;

    top: 0px;
    height: 150px;
}

但是如果图像被剪切了就会显示出来。我尝试将background-size: 100%;替换为background-size: cover;,但效果相同。

我也尝试添加这些行:

-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;

但结果是一样的。

如果我尝试使用background-size: contain来获取图像,则图像会从右侧缩小。

如何在我的div上查看完整图片?

P.S:我已经看到了这个问题css - how to stretch and auto-resize background image,但提供的答案并没有改变我的情况。

编辑: Here您可以看到效果。

提前致谢!

3 个答案:

答案 0 :(得分:0)

使用以下代码行:

background-size: 100% 150px;

因此宽度为100%,但高度始终保持为150px。

请记住,如果您没有为标题指定固定宽度,这会拉伸您的图片。

这里有一个小提琴:https://jsfiddle.net/shbLd8v3/

答案 1 :(得分:0)

如果这是你想要的,请尝试以下

&#13;
&#13;
body {
  padding: 0px;
  margin: 0px;
}
#header {
  background-image: url('http://www.disney.es/sites/default/files/styles/retina-reduction/public/Cars/GENERIC/Section%20Listings/ICE/msf_cars_ice_lst_characters.jpg');
  height: 100%;
  background-position: center;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  -webkit-transition: 800ms all ease;
  -moz-transition: 800ms all ease;
  -ms-transition: 800ms all ease;
  transition: 800ms all ease;
  background-color: #fff;
  min-height: 150px;
  width: 100%;
  padding-top: 10%;
  margin: 0px;
}
&#13;
<div id="header">
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

 background-repeat: repeat-x; 

试试这个,您可以使用background-position: 100%;