【问题标题】:CSS only full size background image centered with correct ratio仅以正确比例居中的 CSS 全尺寸背景图像
【发布时间】:2014-06-14 23:24:37
【问题描述】:

我正在寻找一个仅 HTML-CSS 的解决方案(无 js),以拥有一个适合其整个容器的背景图像,同时尊重其比例并居中。我希望结果与此处实现的相似:http://solemone.de/demos/fullsize-background-image-with-css3-background-size/ but without js

我不想使用js的原因是因为我在加载其他所有内容之后加载js,并且我不希望用户在加载页面时看到不准确的背景显示。

【问题讨论】:

  • 有什么问题:背景尺寸:自动,封面; ?
  • 当图片的宽度小于容器的宽度时似乎不起作用

标签: css background


【解决方案1】:

这就是我要做的。使用 CSS3。 JSFiddle

CSS3:

html { 
  background: url(path/to/image.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

适用于现代浏览器,并随窗口大小缩放。

或仅使用 CSS。 JSFiddle

HTML:

<img src="http://wallpapersus.com/wp-content/uploads/2012/03/cityscapes-city-night-photography-long-exposure.jpg" class="bg" alt="">

CSS:

img.bg 
{
  min-height: 100%;
  min-width: 1024px;
  width: 100%;
  height: auto;
  position: fixed;
  top: 0;
  left: 0;
}

它与旧版和现代浏览器兼容。也可以根据窗口大小进行缩放。

注意:这些方法缩放图像的方式是为了使图像保持良好的比例,以便看起来更好!

【讨论】:

    【解决方案2】:

    你可以这样做

    background: url("path/image.png") center center no-repeat;
    

    与背景的大小搭配:

    background-size: 200px 200px;
    

    背景大小支持像素参数和百分比参数。

    问候!

    【讨论】:

      【解决方案3】:

      试试这个

      body
      {
          background:url(image.png) no-repeat 50% 50%;
          background-size:cover;
      }
      

      50% - 左边居中背景,第二个50% - 居中背景在顶部

      contain - 按对象宽度和高度调整图像,cover - 完全按对象 w/h 调整图像。

      【讨论】:

        猜你喜欢
        • 2012-12-13
        • 1970-01-01
        • 2011-05-02
        • 2013-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多