【问题标题】:How to overlap the table(td) text without using position property如何在不使用位置属性的情况下重叠表格(td)文本
【发布时间】:2019-08-28 18:44:34
【问题描述】:

在这里,我在显示 inline-block 属性中的表格有问题。在我的场景中,我需要在 td 元素中添加 2 个跨度和文本。当我使用它时,文本会包裹到下一行。 这里我需要将文本重叠到跨度中,即跨度不应干扰td 的文本内容。我不想使用位置属性。这是我的简单演示。

table {
  border-collapse: collapse;
  width: 200px;
}

table tr td {
  border: 1px solid;
}

span.leftspan {
  display: inline-block;
  width: 50%;
  height: 20px;
  background-color: skyblue;
}

span.rightspan {
  display: inline-block;
  width: 40%;
  height: 20px;
  background-color: red;
}
<table>
  <tr>
    <td><span class="leftspan"></span><span class="rightspan"></span>12</td>
    <td><span class="leftspan"></span><span class="rightspan"></span>25</td>
  </tr>
</table>

在演示中,2 个数字 (12, 25) 不应换行到下一行。我需要实现这个无位置属性。

【问题讨论】:

    标签: javascript html css css-position


    【解决方案1】:

    在 td 元素上使用 display:flex 并在包含数字的元素中使用 flex-grow: 1 将使该元素填充父 td 元素上的其余空间。然后您可以使用 translateX 变换使它们重叠。查看this answer 以获取有关 flex 和 flex-grow 的更多信息。

    table {
      border-collapse: collapse;
      width: 200px;
    }
    
    table tr td {
      border: 1px solid;
      display: flex;
    }
    
    span.leftspan {
      display: inline-block;
      width: 50%;
      height: 20px;
      background-color: skyblue;
    }
    
    span.rightspan {
      display: inline-block;
      width: 40%;
      height: 20px;
      background-color: red;
    }
    
    span.rest {
      flex-grow: 1;
      transform: translateX(-100%)
    }
    <table>
      <tr>
        <td><span class="leftspan"></span><span class="rightspan"></span><span class="rest">12</span></td>
        <td><span class="leftspan"></span><span class="rightspan"></span><span class="rest">25</span></td>
      </tr>
    </table>

    【讨论】:

    • 文本内容不与跨度重叠。我需要将文本重叠到 span 元素中。
    • 我已经更新了答案,然后使用transform: translateX进行重叠
    【解决方案2】:

    添加了Div,并为Div添加了样式

    table {
      border-collapse: collapse;
      width: 200px;
    }
    
    table tr td {
      border: 1px solid;
    }
    
    table tr td div {
      display: flex;
    }
    
    span.leftspan {
      display: inline-block;
      width: 50%;
      height: 20px;
      background-color: skyblue;
    }
    
    span.rightspan {
      display: inline-block;
      width: 40%;
      height: 20px;
      background-color: red;
    }
    <table>
      <tr>
        <td>
          <div>
            <span class="leftspan"></span><span class="rightspan"></span>12
          </div>
        </td>
        <td>
          <div>
            <span class="leftspan"></span><span class="rightspan"></span>25
          </div>
        </td>
      </tr>
    </table>

    【讨论】:

    • 我不想用 div 包裹 spans
    猜你喜欢
    • 2021-03-19
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    相关资源
    最近更新 更多