【问题标题】:How can I have a single fixed image fit to screen when the body is always centered当身体始终居中时,如何使单个固定图像适合屏幕
【发布时间】:2013-03-08 18:18:33
【问题描述】:

所以也许这正是我将身体居中的方式,因为我在 html 中将其显示为居中的表格。

html {
    display: table;
    margin: auto;
}

body {
    width:100%;
    display: table-cell;
    vertical-align: middle;
}

#background{
    width:100%;
    height:100%;
    position:fixed;
    background-image:url('image.jpg'); 
    background-repeat: no-repeat;
    background-size:cover;
}

基于该代码,我可以看到图像将从主体的开头开始,从中心开始,因此图像将从那里开始,并且我有不应该存在的空白空间;我希望正文中的内容居中,但背景不应该如此,这样它才能以正确的方式适合屏幕。我尝试将我的中心代码转移到容器中,但没有奏效。我环顾了一两个小时,所有的答案都没有为我工作。知道如何解决这个问题吗?

【问题讨论】:

  • 我不确定你在问什么?你能在 jsFiddle 或其他地方举个例子吗?因为position: fixed; 将从页面流中取出一个元素并将其定位到与视口相关的位置,而不是父元素。这是你正在经历的吗?
  • 我认为他只是想要全屏背景。没有列出实际职位。 top: 50%; left: 50%; margin: -50% 0 0 -50%; 之类的。
  • 这里是显示我的问题 jsfiddle.net/xJJ2V/17 的 jsfiddle。位置必须固定的原因是,当所有内容向下滚动时,图像会停留在那里并且不会继续拉伸

标签: html css background center


【解决方案1】:

您是否重置了页面的边距?

html {
  margin: 0;
  padding: 0;
 }

body {
  margin: 0;
  padding: 0;
 }

另外,如果您想要的结果是全屏背景,为什么不这样做:

body {
  background: url(images/bg.jpg) no-repeat center center fixed; 
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
background-size: cover;
}

查看此链接了解替代方法:http://css-tricks.com/perfect-full-page-background-image/

【讨论】:

  • 我正在尝试使正文内容以固定的背景居中并适合全屏...如果正文未居中则有效
【解决方案2】:

不让你的身体居中怎么样,你能把它包在一个容器里吗? “mainContainer”并将其居中?

已编辑:这是从你的 http://jsfiddle.net/amyamy86/C4Spd/987654321@ 分叉出来的小提琴

<html>
    <body>
       <div id="background"></div>
       <div id="outerContainer">
           <div id="mainContainer">
               <div id="box">
                   <p>This is some content</p>
               </div>
           </div>
       </div>
    </body>
</html>

#outerContainer {
    display: table;
    margin: auto;
}
#mainContainer{
    width:100%;
    display: table-cell;
    vertical-align: middle;
}
#background {
    width:100%;
    height:100%;
    background-image:url('http://mytwopiasters.files.wordpress.com/2011/01/ocean.jpg');
    position:absolute;
    background-repeat: no-repeat;
    background-size:cover;
}
#box {
    text-align:center;
    width:100px;
    position:fixed;
    height:100px;
    background:#fff;
    border:1px #000 solid;
}

【讨论】:

  • @RyanSaxe 该网站是否对公众开放?如果您不介意我查看您的完整 html/css,那么我可以修改 Firebug。
  • 不,目前还没有,但这里有一个快速的 jsfiddle,我整理了它的基础知识...jsfiddle.net/xJJ2V/17
  • @RyanSaxe 太棒了,请投票和/或将问题标记为已回答:) 非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-29
  • 2016-08-09
  • 2015-01-27
  • 2020-05-21
  • 2021-07-23
  • 2018-04-24
  • 2017-03-22
相关资源
最近更新 更多