【问题标题】:CSS: align image icon of any size in the middle-center of a boxCSS:在框的中间对齐任意大小的图像图标
【发布时间】:2014-04-27 15:43:35
【问题描述】:

我浏览了几篇文章并访问了其他网站,但仍然找不到解决方案。 我尝试了几个建议都无济于事,从昨天到今天我已经尝试了几个小时来寻找解决方案。 所以,如果这个问题看起来重复,请原谅我,但事实是没有一个解决方案适合我。 事实上,在重建整个页面之前,我会感谢这里有人的帮助。 我的老板“只是”希望看到图标适合盒子的中间位置。 由于框内没有文本,因此垂直对齐:中间;不适用。图片可以有不同的尺寸,所以我不能指望一个固定的尺寸来定位它。

谢谢

img {
    max-width: 100%;
    max-height: 100%;
}
.imageHolder {
    margin: 2px 10px;
    padding: 5px;
    border: 1px solid #999;
    background-color: white;  
    display: inline-block;  
    vertical-align: middle;
}
#contenido .logo-radio .imageHolder {
    width: 72px;
    height: 72px;  
}

<div class="logo-radio">
    <article class="imageHolder">
        <a href="#"><img src="#" alt="Logo AM 750"></a>
    </article>
</div>

Fiddle

【问题讨论】:

  • 好吧,如果您有容器的特定尺寸,并且您知道图像的尺寸,为什么不简单地计算 2,然后添加相应的填充/边距?
  • 这就是我在写的时候解释的:“图像可以有不同的尺寸,所以我不能指望一个固定的尺寸来定位它。”

标签: jquery html css image vertical-alignment


【解决方案1】:

我找到了解决方案。代码如下:

.imageHolder {
    text-decoration: none;
    display: inline-block;
    height: 72px;
    width: 72px;
    overflow: hidden;
    position: relative;
    border: 1px solid silver;
    vertical-align: middle;
    margin: 5px;
    padding: 3px;
}

.imageHolder img {
    max-width: 100%;
    max-height: 100%;
    margin: auto;
    display: block;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

我创建了一个jsfiddle 来展示它:

【讨论】:

    【解决方案2】:

    我已经看到通过以下两种方式之一完成此操作:

    1. 将其设为背景图片:

      a{
       display: block;
       width: 100%;
       height: 100%;
       background: url(yourimage.jpg) center no-repeat;
       background-size: 100%;
      }
      
    2. 绝对定位:

      .imageHolder {
       margin: 2px 10px;
       padding: 5px;
       border: 1px solid #999;
       background-color: white;  
       display: inline-block;  
       vertical-align: middle;
       position: relative;
      }
      #contenido .logo-radio .imageHolder {
       width: 72px;
       height: 72px;  
       position: absolute;
       top: 50%;
      }
      #contenido .logo-radio .imageHolder a{ 
       position: absolute;
       top: 50%;
      }
      img {
       max-width: 100%;
       max-height: 100%;
       position: relative;
       top: -50%;
      }
      

    【讨论】:

    • 你试过用 top:50% 绝对定位 img 然后应用 transform:translateY(-50%) 吗?
    【解决方案3】:

    &lt;div class="logo-radio" align="center"&gt;

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-25
    • 2014-06-04
    • 2014-09-26
    • 2017-08-04
    • 1970-01-01
    • 2014-02-05
    • 2011-08-11
    • 2012-08-17
    相关资源
    最近更新 更多