【问题标题】:Full height Background Image with centered width具有居中宽度的全高背景图像
【发布时间】:2013-07-27 00:17:16
【问题描述】:

我有一个宽高比为 4:3 的图片作为背景图片。
我的第一个目标是拥有一个全高图像,根据高度调整大小,宽度可变(取决于高度)。图片应该居中。
例如,如果我有一个 16:9 的视口,它应该显示以左右空格为中心的背景图像。

我尝试了不同的方法(以 16:9 视口的 4:3 图像为例)。
首先,background-sizecontaincover 都应用于<body> 标签:

  • 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>不是覆盖了整个视口吗?
  • 尝试contain并添加body, html {min-height:100%;}
  • 在@Pete 的建议下,它确实有效:)

标签: html css background-image


【解决方案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;
 }

现在我只是添加一些其他背景图案以避免左右空白处出现单色

【讨论】:

    【解决方案2】:

    更新你的 CSS:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多