【问题标题】:css background not working in divCSS背景在div中不起作用
【发布时间】:2016-02-22 20:53:52
【问题描述】:

我的代码有一点问题,但我找不到问题出在哪里。 如果我在 css 中使用带有“body”标签的背景,它会显示,但如果我对 div 做同样的事情,它仍然是白色的。

代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="css/style.css">

    <script src="js/jquery-1.11.3.min.js"></script>
    <script src="js/script.js"></script>
</head>
<body>
    <div id="one">
        <header>
        </header>
        <section>
        </section>
        <footer>
        </footer>
    </div>
</body>
</html>

css

#one{
    background: url(../img/background.jpg);
    background-repeat: repeat;
    background-size: cover;
    display: block;
    height: 100%;
    width: 100%;
}

和一个javascript(只是以防万一)

$(function(){
    var x = 0;
    setInterval(function(){
        x-=1;
        $('body').css('background-position', 0 + 'px '+ x +'px');
    }, 200);
})

我尝试使用“body”并且它有效,但仅适用于 body :(

【问题讨论】:

  • 你为什么不展示你失败的尝试???也许我想念你的问题。是跟 CSS 还是 js 相关还是两者都有?
  • 似乎工作正常:jsfiddle.net/4eweL11j。你调试过吗?控制台有错误吗?
  • px #one{...} css 中给出高度和宽度
  • 好像你在模仿 CSS 规则:html, body { height: 100%; width: 100%; } 否则你的 DIV 不会定义任何大小:**编辑:** @RoryMcCrossan 哦,看看你的 jsFiddle ;)
  • Css 我猜。我没有来自控制台的任何报告,只是没有显示背景,只有在 css 中使用“body”标签时才能看到

标签: javascript jquery html css background


【解决方案1】:

要在 #one div 中使用 100% 高度,您还需要为 bodyhtml 标签设置 100% 高度。没有此规则,100% 宽度将起作用。 因此,将以下行添加到您的 css 文件中:

html, body { height: 100%; }

【讨论】:

    【解决方案2】:

    这是您尝试使用的完整 HTML 吗?在您提供给我们的代码中,您的 div 没有大小,因为它没有内容。在 snnipet 中,您可以看到您的代码,其内容已添加到 div#one

    随机 google 图像用作测试目的的背景 .

    $(function(){
            var x = 0;
            setInterval(function(){
                x-=1;
                $('body').css('background-position', 0 + 'px '+ x +'px');
            }, 200);
        })
    #one{
        background: url(http://7-themes.com/data_images/out/76/7030767-3d-background-wallpaper.jpg);
        background-repeat: repeat;
        background-size: cover;
        display: block;
        height: 100%;
        width: 100%;
    }
      <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="css/style.css">
    
        <script src="js/jquery-1.11.3.min.js"></script>
        <script src="js/script.js"></script>
    </head>
    <body>
            <div id="one">
                <header>
                  <p>Sample Header</p>
                </header>
                <section>
                </section>
                <footer>
                </footer>
            </div>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      • 2020-03-29
      • 2016-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多