简体   繁体   中英

Why absolutely positioned element in a table cell is wrapping?

Consider the following: (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;
}

Why the absolutely positioned button is wrapping?

I could solve it by:

button {
  white-space: nowrap;
}

but I'm really interested to know why this wrapping is happening, and whether there is a better way to solve this.

It is wrapping to avoid overflowing the parent container in this case. It is still overflowing it because you have too long of a single word, but the behavior is to try to not overflow it. If you change your demo to have more text in your other button you would see it wraps as well once it exceeds the table cell width.

Use the white-space: nowrap if you want to avoid this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM