【问题标题】:Why absolutely positioned element in a table cell is wrapping?为什么表格单元格中的绝对定位元素会换行?
【发布时间】:2013-06-04 13:11:31
【问题描述】:

考虑以下问题:(Live Demo)

HTML:

<table>
  <tbody>
    <tr>      
      <td class="col1">
        <button class="btn btn-small">Do Something</button> 
      </td>
      <td class="col2"></td>
    </tr>
    <tr>
      <td class="col1"></td>
      <td class="col2">
        <span style="position: relative">
          Text 
          <button class="btn btn-small" 
                  style="position: absolute; 
                         top: 0; 
                         left: 210px">
            Do Something
          </button>
        </span>
      </td>
    </tr>
  </tbody>
</table>

CSS:

tr {
  height: 100px;
}
td {
  border: 1px solid black;
}
.col1 {
  width: 150px;
}
.col2 {
  width: 200px;
}

为什么绝对定位的按钮会换行?

我可以通过以下方式解决它:

button {
  white-space: nowrap;
}

但我真的很想知道为什么会发生这种包装,以及是否有更好的方法来解决这个问题。

【问题讨论】:

  • position:absolute; 有什么理由吗?与上述情况一样,如果我用position:relative 替换绝对定位,保持left: 176px;top:0; 就可以达到目的。
  • @Nathan:是的。我不希望按钮影响其他单元格元素的定位(在本例中为Text)。例如,如果您尝试将.col2 宽度更改为50px,您会看到position: relativeText 不再垂直居中:jsbin.com/ujilig/1/edit
  • @NathanLee 即使位置相对,如果你让它更长,它会再次换行,例如“Do Somethiiiiiiiiiiiiiiiinnnnnnnnnnnnnnnnnng”。我认为由于没有为按钮分配宽度,并且没有rightleft,因此按钮将尝试采用最小尺寸。 (通过包装)

标签: html css css-position css-tables


【解决方案1】:

在这种情况下,它是包装以避免溢出父容器。它仍然溢出它,因为你有一个太长的单词,但行为是尽量不溢出它。如果您将演示更改为在其他按钮中包含更多文本,您会看到它在超出表格单元格宽度时也会换行。

如果您想避免这种情况,请使用white-space: nowrap

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    • 2012-12-23
    相关资源
    最近更新 更多