无法将完整图像显示为css背景

时间:2014-12-18 19:57:00

标签: html css

我有一个大图像,我想使用div的背景。我想显示完整的图像,没有没有scalling&裁剪。试过这段代码,但它不起作用。我在这里想念的是什么?

<html>
<head>
<style type="text/css">
body {height:100%; overflow-y:hidden;}
.bgimg {
    background-image: url(DSC_0076.jpg);
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    height: 100%;
    width: 100%;

}
    .txt{
        padding-top: 200px;
    padding-right: 100px;

    text-align: right;
    }
</style>
</head>
<body>
<div class="bgimg">
    <h1 class="txt">
        Dummy Text
    </h1>
</div>
<div id="disqus_thread"></div>
    <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
    <footer>
        <p>This site is under construction, please wait for some time for the details.</p>
    </footer>
</body>
</html>

这是它出现的方式: enter image description here

然而实际图像如下所示: enter image description here

5 个答案:

答案 0 :(得分:1)

你的CSS需要一些工作,因为如果没有设置HTML高度,那么100%高度的主体就没有任何意义。你基本上是在说;让我的身体占据其容器的100%,这是HTML,但默认情况下HTML是自动的,并且只有足以容纳内容,有效地使身体的100%高度毫无价值,除非你在html上指定100%高度为好吧,它占用浏览器窗口。

此外,身体上的溢出可能导致裁剪。

html, body { height: 100%; }

如果您希望背景图像完整显示,则需要使容器与背景大小相同。背景图像永远不会调整其设置的容器的大小。只是没有这样的工作。

答案 1 :(得分:0)

将所有<style>代码移至<head>代码前的<body>代码

尝试将此属性添加到bgimg:

position: absolute;

如果您希望图像显示在所有内容后面,请将此添加到bgimg中:

z-index: -1;

在此处查看: http://jsfiddle.net/prw0pqgf/

答案 2 :(得分:0)

background-size: 100% 100%;

应显示您的完整背景。

查看&#34;播放&#34;在封面部分

http://www.w3schools.com/cssref/css3_pr_background-size.asp

不要忘记明确设置div的大小:

width: 1024px;
height: 768px;

http://jsfiddle.net/29ysobnt/2/

答案 3 :(得分:0)

要使背景图像响应,请将高度除以宽度,然后将div的最小高度设置为结果的vw百分比。

例如,您的图片是1024px x 768px。 768/1024 = 75.所以,添加你的风格:

&#13;
&#13;
.bgimg {
  min-height: 75vw;
}
&#13;
&#13;
&#13;

答案 4 :(得分:-1)

http://jsfiddle.net/903q9kzb/2/

通过向其他元素添加一些大小属性来修复。重要的是,body,html的高度设置为html,body{height: 100%;}

请记住始终在css文件中使用样式而不是直接在html中使用。这是一个坏习惯,看起来很难看!