【问题标题】:Vertically center icon between variable-height content and bottom of table cell在可变高度内容和表格单元格底部之间垂直居中图标
【发布时间】:2015-10-24 04:29:05
【问题描述】:

我在某些文本下方的单元格中显示一个图标,其确切长度/高度事先未知(基于用户输入或翻译),并希望它在文本和文本之间垂直居中单元格底部。

让它与单元格的中心对齐很容易(vertical-align: center、绝对定位等),但让它在文本下方居中就不是那么容易了。形象化我的意思:

红线是找到单元格的中心,这是我们可以得到它的地方。蓝线是文本的底部,绿线交叉的地方是我们想要的位置。

我目前拥有的示例:http://plnkr.co/edit/RIaXLzPtQiqLK9XBcmD0

事情并不容易:

  • 除了内容的高度之外,表格单元格没有高度,因此我们不能有一对 div,一个在另一个之下,而底部占据其余部分。
  • 显示图标的单元格旁边的单元格内容的高度无法预先确定,因此我们无法在单元格上设置高度并期望它始终为真
  • “TITLE TEXT”的实际内容,即长度和高度,现在已经提前知道了。用户输入的内容或翻译可能会导致多行中断
  • 必须(合理地)支持 IE9+

如果不知道周围元素的大小,有没有办法让图标垂直居中在文本底部和表格单元格底部之间?

【问题讨论】:

标签: html css


【解决方案1】:

使用 jQuery 和一些数学,这可能对你有用:jsFiddle(我比其他网站更习惯于摆弄)。

jQuery:

$(document).ready(function(){
   //get total height of cell
   var padding = $('.cell').height();
   //subtract height of title text and top 20px
   padding = padding - $('.titleText').height() - 20;
   //split in half for middle
   padding = padding/2;
   $('.iconContainer').css('padding-top', padding + 'px');
});

和 HTML:

<table>
  <tr>
    <td>
      This is a<br />
      tall cell<br />
      to<br />
      make<br />
      the<br />
      other<br />
      tall
    </td>
    <td class="cell">
      <div class="titleText">Title Text</div>
      <div class="iconContainer"><div class="icon">&nbsp;
      </div></div>
    </td>
  </tr>
</table>

和 CSS:

table {
  width: 400px;
}

td {
  width: 50%;
  border: thin solid black;
  position: relative;
}

.titleText {
  position: relative;
  top: 20px;
  width: 100%;
  text-align: center;
  text-transform: uppercase;
  font-size: 20px;
}
.cell
{
    vertical-align: top;
}
.icon {
  background-image: url( 'http://icons.iconarchive.com/icons/tinylab/android-lollipop-apps/32/Skala-icon.png' );
  width: 32px;
  height: 32px;
  margin: auto;
}

编辑:仅使用 Javascript,这是另一种解决方案(原理相同):http://plnkr.co/edit/i1m1lulL7OgAe0ykY6eX?p=preview

【讨论】:

    猜你喜欢
    • 2013-10-12
    • 1970-01-01
    • 2014-05-26
    • 2019-05-15
    • 1970-01-01
    • 2010-09-08
    • 2018-03-21
    • 2014-06-28
    • 2015-04-18
    相关资源
    最近更新 更多