如何使背景标题图像扩展到浏览器的全宽

新手上路,请多包涵

仍在学习 CSS 的工作原理。目前,我正在尝试使背景图像覆盖整个标题,而顶部/右侧/左侧没有任何间隙。

我尝试了其他几种选择,但似乎无法移动此图像。

(即添加 html,但我想将其与该文件分开。我也尝试过使边距为 0)

 <!--EXAMPLE1-->
.splash_img {
background-repeat:no-repeat;
background-position: center top;
display:block;
margin:0px auto;
}

<!--EXAMPLE2-->
.splash_img:{
background-image:url("Images/bakemock.jpg") no-repeat center;
background-size:100% 100%;
height:630px;
}

它继续停留在浏览器的右上角。目前这就是我所拥有的。

 <head>
    <div class="splash_img">
        <img src="Images/bakemock.jpg" alt="bake"/>
    </div>
</head>

.splash_img:{
background-image:url("Images/bakemock.jpg") no-repeat center;
background-size:100% 100%;
height:630px;
}

原文由 Jen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 307
2 个回答

这些行:

 <head>
   <div class="splash_img">
     <img src="Images/bakemock.jpg" alt="bake"/>
   </div>
</head>

不能工作。

您不能将 <div> <img> 和许多其他元素放在 <head> 标签内。您的构建器标签应该仅位于 <body> 中。而 <body> 里面不能有 <head> 标签。

两种可能性

  1. If this section is inside the <body> and is not refering to the <head> above the <body> then change it to <header> or something like that
  2. 如果此部分位于 <body> 之上,删除其中的 html 元素并将 <header> 标签放入 <body> 部分

一个有效的 HTML 应该是这样的:

 <!DOCTYPE html>
<html>
<head>
   <title>Some title</title>
   <!-- meta tags, js scripts, css styles etc -->
</head>
<body>
   <!-- div tags, spans, imgs, etc are ok -->
   <!-- but you cannot put a <head></head> tag here -->
</body>
</html>

同样重要的注意事项

您不能放置 background-image: 并指定超过背景图像 src 本身。如果你想指定的不仅仅是源使用 background: 代替

background: url("/Images/bakemock.jpg") no-repeat center;

最后一件事当然是浏览器给 <html><body> 标签的默认填充/边距,你应该覆盖:

 html, body {
   padding:0px;
   margin:0px;
}

综上所述

此代码将为您工作

<!DOCTYPE html>
<html>
<head>
    <title>Some title</title>
    <style>
        header {
            background: url("/Images/bakemock.jpg") no-repeat center;
            background-size: 100% 100%;
            height: 630px;
        }
        html, body {
            padding:0px;
            margin:0px;
        }
    </style>
    <!-- meta tags, js scripts, css styles etc -->

</head>
<body>
    <!-- div tags, spans, imgs, etc are ok -->
    <!-- but cannot put a <head></head> tag here -->
    <header>
    </header>
</body>
</html>

你也可以在这里看到它:

JSFiddle

希望能帮助到你。如果您有任何问题,请告诉我。

原文由 Jaqen H‘ghar 发布,翻译遵循 CC BY-SA 3.0 许可协议

你可以这样做:

HTML:

 <div class="splash_img">
    <img src="Images/bakemock.jpg" alt="bake"/>
</div>

CSS:

 .splash_img {
  background: url(Images/bakemock.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

原文由 RasmusGlenvig 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题