【问题标题】:Background-size: cover on body is higher than viewport (even though body is 100% height)背景尺寸:身体上的覆盖物高于视口(即使身体是 100% 高度)
【发布时间】:2017-04-15 13:54:40
【问题描述】:

我想在我的body 中使用背景图片。背景图像应覆盖视口(与屏幕的宽度和高度相同)。我有以下代码,但背景图像显示得比视口/屏幕高:图像底部延伸到折叠下方。可能是背景图像没有被身体上的 100% 高度裁剪。

    html {
    	height:100%;
        }
    
    body { 
     	height:100%;
    	background-image:url("http://lorempixel.com/400/200/");
    	background-position: top left;
    	background-size:cover;
    	background-repeat:no-repeat;
    	}
    
    main {
    	max-width:80rem;
    	height:1000px;
    	background-color: rgba(0,0,200,0.5);
    	}
<main></main>

【问题讨论】:

  • @vals 注意到你删除的答案,你知道为什么会这样吗?
  • 我相信有身体背景的特殊情况,我认为这有什么问题,但我一直没能找到它

标签: css background-image


【解决方案1】:

我认为这种行为的原因是规范的这一部分:

根元素的背景成为画布的背景并覆盖整个画布,锚定在同一点(对于“背景位置”),就像它只为根元素本身绘制时一样。根元素不再绘制此背景。

所以这将是 body

的一个特殊问题

在这个 sn-p 中,body-pseudo 可以正常工作

html,
body {
  height: 100%;
}

body::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-image: url("http://lorempixel.com/400/600/");
  background-position: top left;
  background-size: cover;
  background-repeat: no-repeat;
  z-index: -1;
}

main {
  max-width: 80rem;
  height: 1000px;
  background-color: rgba(0, 0, 200, 0.5);
}
<main></main>

【讨论】:

  • 我删除了我的并更新了你的,加上 1 ...希望你不介意:)
  • @LGSon 当然我不介意 :-) 但是你的回答没问题,我不想发布我的替代方案。只是想明确这个问题是一个特例body 周围。不管怎样,这样就好了。 ...谢谢 :-)
【解决方案2】:

您可以在 100 的视口测量中将最小宽度和最小高度应用到主体。

见下面的sn-p

body { 
    height:100%;
    min-width:100vw;
    min-height:100vh;
    background-image:url("https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSnfXp5RSFk2ZfOmIl7EMvUHEW0bzWBowc6NtDFkG3M7r2Xljl2");
    background-position: top left;
    background-size: cover;
    background-repeat:no-repeat;
    margin:auto;
    }
<body>
<main>  
</main> 
</body

【讨论】:

  • 当高度低于图像的比例高度时,这并不能阻止它被裁剪......这有意义吗?
猜你喜欢
  • 2017-08-19
  • 1970-01-01
  • 1970-01-01
  • 2013-05-13
  • 1970-01-01
  • 2016-04-08
  • 2014-07-29
  • 1970-01-01
  • 2012-04-20
相关资源
最近更新 更多