调整背景图像CSS的大小

时间:2014-11-13 22:43:59

标签: html css

我正在尝试将背景图片添加到我的HTML header中,但它不按照我想要的方式工作。

部首:

<header class="background_image">

</header>

目前只有当我的CSS如此时才会显示图片:

.background_image {
    background-image: url(image-path("header-bg.jpg"));
    height: 500px;
}

即便如此,只显示部分图像

我环顾四周,尝试添加不同的CSS属性组合,例如:

background-size: auto;
width: 100%;
position: absolute;
top: 0;
left: 0;
background-size: cover;
background-position: center center;

但是他们每个人都有一个很细的想象。起初我以为图像没有加载,但我认为只显示了一小部分,我认为是黑色的细线

2 个答案:

答案 0 :(得分:3)

我认为你已回答了自己的问题,&lt;标题&gt;需要有一个height属性来应用可见的背景图像。

标准建议不能仅使用CSS自动将选择器调整为背景图像大小......如果这就是您所追求的。

话虽如此,取决于您的布局的其余部分...查看此代码段(也在jsfiddle上):

&#13;
&#13;
div{
    background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
    background-size: contain;
    background-repeat: no-repeat;
    width: 100%;
    height: 0;
    padding-top: 66.64%; /* (img-height / img-width * width) */
                /* (853 / 1280 * 100) */
}
&#13;
<div></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

image-path("header-bg.jpg")

有什么用?

那是我的猜测。 CSS中图像的正确格式是:

background-image: url(path/to/image.png);

如本例所示:

.background_image {
    background-image: url(http://placehold.it/1200x500); // <-- This right here.
    height: 500px;
}

此外,如果只是标题会切断您的图片,我强烈建议您查看background-size非数字属性,例如containcover