【问题标题】:Keep image centered保持图像居中
【发布时间】:2014-06-16 22:54:34
【问题描述】:

我有这个简单的 html:

<img src="http://i1.ytimg.com/vi/XWGszmviDpA/maxresdefault.jpg" class="bg">

到目前为止,只要窗口不小于图像,我就可以正确地将图像居中。现在,当窗口较小时,我无法将脸保持在中间!我怎样才能解决这个问题? 对我来说,图像高度保持 100% 的窗口很重要。

我的 CSS:

img.bg {  
  width: auto;
  height: 100%;
  position: fixed;
  left:0;
  right:0;
  margin:0 auto;   

}

谢谢!

http://jsfiddle.net/67jDp/1/

【问题讨论】:

  • 图片可以作为背景显示吗?
  • 试试max-width:100%,但请记住,它可能会破坏纵横比。 @MarcAudet 的背景图片建议更可靠,如果可行的话。

标签: html css


【解决方案1】:

尝试将其用作background-image。 CSS:

.bg {
    background-image:url('http://i1.ytimg.com/vi/XWGszmviDpA/maxresdefault.jpg');
    width: auto;
    height: 100%;
    position: fixed;
    left:0;
    right:0;
    margin:0 auto;   
    width:70%; //Custom dimension
    background-position:center;
    background-size:cover; 
}

演示:http://jsfiddle.net/lotusgodkk/67jDp/2/

【讨论】:

    【解决方案2】:

    尝试将图像设置为div 的背景,而不是img 标签

    http://jsfiddle.net/CeVwN/1/

    .bg {
        background-image:url('http://i1.ytimg.com/vi/XWGszmviDpA/maxresdefault.jpg');
        background-position:center;
        background-size: auto 100%;
        background-repeat: no-repeat;
        width: auto;
        height: 100%;
        position: fixed;
        left:0;
        right:0;
        margin:0 auto;
    }
    

    【讨论】:

      【解决方案3】:

      你可以用很少的 javascript 来使用它

      css:

      img.bg {
          height: 100%;
          position: fixed;
          left:50%;
      }
      

      JS:

      var i = $('img');
      var w = i.width();
      
      i.css({marginLeft: -w/2});
      
      $( window ).resize(function() {
          i.css({marginLeft: -w/2});
      });
      

      演示:http://jsfiddle.net/67jDp/4/

      【讨论】:

        【解决方案4】:

        设置width to 100% 以始终获取容器的宽度。然后,设置height to auto 允许比例:

        img.bg {
            width: 100%;
            height: auto;
            position: fixed;
            left:0;
            right:0;
            margin:0 auto;   
        }
        

        记得设置max-width 以在必要时停止扩展。

        【讨论】:

          猜你喜欢
          • 2018-11-22
          • 2013-11-01
          • 1970-01-01
          • 2018-12-11
          • 2014-01-02
          • 2015-02-21
          • 2016-05-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多