首页 > 解决方案 > “垂直对齐:顶部”不适用于表格单元格的图像+跨度内容,尽管所有儿童元素都是非块状的

问题描述

我需要text标签位于以黄色背景突出显示的表格单元格的顶部。

在此处输入图像描述

虽然vertical-align: top;定义td的选择器和图像元素是inline-block(不是block),表底部的“文本”。

.table {
  width: 200px;
  background: #FCF3CF;
}

.table td {
  vertical-align: top;
}


.image-defaultBackgroundUnderlay {
  
  display: inline-block;
  
  width: 60px;
  height: 60px;

  position: relative;
  border: 1px solid #ececec;
  background: white;
}
  
.image-imageLayer {

  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;

  background-position: center;
  background-repeat: no-repeat;
  background-size: contain;
}
<table class="table">
  <tr>
    <td>
      <div class="image-defaultBackgroundUnderlay">
        <div class="image-imageLayer" style="background-image: url(https://dummyimage.com/960x540/626ffc/e6e6e6.png);"></div>
      </div>
      <span>text</span>
    </td>
  </tr>
</table>

请不要包装解决方案

标签: htmlcss

解决方案


您需要veritcal-align:top在图像上而不是td

.table {
  width: 200px;
  background: #FCF3CF;
}

.table td {
  /*vertical-align: top;*/
}

.image-defaultBackgroundUnderlay {
  display: inline-block;
  width: 60px;
  height: 60px;
  position: relative;
  border: 1px solid #ececec;
  background: white;
  vertical-align:top
}

.image-imageLayer {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  background-position: center;
  background-repeat: no-repeat;
  background-size: contain;
}
<table class="table">
  <tr>
    <td>
      <div class="image-defaultBackgroundUnderlay">
        <div class="image-imageLayer" style="background-image: url(https://dummyimage.com/960x540/626ffc/e6e6e6.png);"></div>
      </div>
      <span>text</span>
    </td>
  </tr>
</table>

在您的情况下,元素已经与顶部对齐。为了更好地理解这里是一个插图:

.table {
  width: 200px;
  background: #FCF3CF;
}

.table td {
  height: 150px;
}

.image-defaultBackgroundUnderlay {
  display: inline-block;
  width: 60px;
  height: 60px;
  position: relative;
  border: 1px solid #ececec;
  background: white;
}

.image-imageLayer {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  background-position: center;
  background-repeat: no-repeat;
  background-size: contain;
}
no alignement
<table class="table">
  <tr>
    <td>
      <div style="border:2px solid red;">
        <div class="image-defaultBackgroundUnderlay">
          <div class="image-imageLayer" style="background-image: url(https://dummyimage.com/960x540/626ffc/e6e6e6.png);"></div>
        </div>
        <span>text</span>
      </div>
    </td>
  </tr>
</table>
aligned to top
<table class="table">
  <tr>
    <td style="vertical-align:top;">
      <div style="border:2px solid red;">
        <div class="image-defaultBackgroundUnderlay">
          <div class="image-imageLayer" style="background-image: url(https://dummyimage.com/960x540/626ffc/e6e6e6.png);"></div>
        </div>
        <span>text</span>
      </div>
    </td>
  </tr>
</table>

因此vertical-align会将包含图像和文本的整行对齐到顶部,并且不会将所有元素对齐到顶部。每个元素的对齐方式将取决于vertical-align应用于它们


推荐阅读