【问题标题】:Centering an image within a div, both axes在 div 中居中图像,两个轴
【发布时间】:2014-01-22 21:05:41
【问题描述】:

我正在尝试使图片适合div 框。但是,我需要对齐它,以便图片的 center 实际上位于div 的中心。图片的尺寸各不相同。

在下面的示例中,我首先需要使用max-width: 100% 调整宽度以适合图片。但是,现在 Y 轴没有居中(图片的底部被切掉而不是下半部分上半部分)。

我怎样才能像下图那样居中?

【问题讨论】:

  • 哇...这么有吸引力的问题... :)
  • 你能不能给一些代码或者jsFiddle...
  • 我爱上了这个问题 XD
  • 你为什么要剪掉这位漂亮的女士? :)
  • @Patrick:运气不好的人..尝试更改图像以获得答案..:D

标签: css


【解决方案1】:

如果您乐于让图片成为 background-image 而不是实际的 img 元素,那么以下应该可以工作:

 #imagediv { 
   background: url(images/bg.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
   background-size: cover;
  }

【讨论】:

    【解决方案2】:

    给你:

    .container {
        background-image : url('http://khongthe.com/wallpapers/people/cute-face-218642.jpg'); /* put your image here */
        width: 420px; /* as you want */
        height: 420px; /* as you want */
        background-position: center center;
        background-repeat: no-repeat;
        /*background-size : cover;*/ /*bonus*/
    }
    

    并使用这个 html :

    <div class="container"></div>
    

    JsFiddle example.

    这是一个经典问题。顺便说一句,我很确定您可以在 Google 上找到它。和我的 sn-p 一起玩吧。

    【讨论】:

      猜你喜欢
      • 2012-01-03
      • 2011-02-11
      • 1970-01-01
      • 2013-06-26
      • 2012-07-02
      • 1970-01-01
      相关资源
      最近更新 更多