全高度背景图片,宽度居中

3
我有一张宽高比为4:3的图片要用作背景图像。
我的首要目标是拥有一个全屏高度的图像,根据高度自动调整尺寸,宽度可变(取决于高度)。 图片应该居中显示。
例如,如果我有一个16:9的视口,它应该以居中的方式显示背景图像,并留有左右空白区域。

我尝试了不同的方法(以使用16:9视口的4:3图像为例)。
首先,将background-size应用于<body>标签,其中包含containcover

  • 使用cover,它会保持纵横比,但会在顶部和底部裁剪图像
  • 使用contain,它不会覆盖整个视口,只覆盖body

还可以使用background-size: auto 100%;产生与contain相同的效果

这是我使用的CSS代码:

 body#home {
  background-image: url(../bg.jpg);
  background-size: auto 100%;
  -moz-background-size: auto 100%;
  -webkit-background-size: auto 100%;
  -o-background-size: auto 100%;
  background-position: center;
  background-repeat: no-repeat;
 }

你的<body>是否覆盖整个视口? - Yotam Omer
1
尝试使用 contain 并添加 body, html {min-height:100%;} - Pete
在@Pete的建议下,它确实起作用了 :) - Kropot
2个回答

1
感谢 @Pete,有了这段代码它真的起作用了:
html, body {
  min-height: 100%;
}
body#home {
  background-image: url(../ppersia-home.jpg);
  background-size: contain;
  -moz-background-size: contain;
  -webkit-background-size: contain;
  -o-background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
 }

现在我只需要添加一些其他的背景图案,以避免左右空白处的单色。

0

更新你的 CSS:

background-position: center center; /* needs horizontal and vertical positions */
background-size: contain; /* use contain so your image fits inside */

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接