【问题标题】:Can overlapping colspan on table cells shrink-to-fit?表格单元格上的重叠 colspan 可以缩小以适应吗?
【发布时间】:2017-02-04 12:01:10
【问题描述】:

我一辈子都想不通这个。取一个有 2 行的表格,每行有 2 个单元格。右上角和左下角的单元格设置为colspan="2"(因此该表实际上有 3 列)。如果非 colspan 单元格内部有一个 100×100 的图像,而 colspan 单元格有一个 200×100 的图像,你会期望表格宽度大约是 300,对吧?不不不!它更像是 400。

看到这支笔:http://codepen.io/sandwich/pen/apYPdL

似乎colspan'd 单元格对宽度很贪心,这与缩小单元格以适应内容的典型表格大小相反。

任何人都可以阐明这种行为吗?在笔中,所需的结果是前两行的大小与添加第三行时的大小相同,但不必添加第三行。

【问题讨论】:

    标签: html html-table sizing


    【解决方案1】:

    如果非 colspan 单元格内部有一个 100×100 的图像,而 colspan 单元格有一个 200×100 的图像,您会希望表格宽度大约为 300,对吧?

    如果 <table>border-collapse:collapse 但它是 separate 和 20px 左右边框,那可能是 2 列的 80px 额外。至少是 380 像素。

    试试table-layout:fixed,默认是auto。使用fixed 可以让您更好地控制表的行为。

    CODEPEN

    片段

    // Toggle visibility of 3rd row, which has no spanned cells.
    $(".toggle_3rd_row").click(function() {
      $(".row_3").fadeToggle();
    });
    
    // Toggle applying CSS widths to <td>s
    $(".toggle_widths").click(function() {
      $("table").toggleClass("defined_sizes");
    })
    body {
      padding: 20px;
    }
    img {
      display: block;
    }
    table {
      width: 400px;
      margin: 20px 0;
      table-layout: fixed;
    }
    table.defined_sizes .cell_1-1 {
      width: 100px;
    }
    table.defined_sizes .cell_1-2 {
      width: 220px;
    }
    table.defined_sizes .cell_2-1 {
      width: 220px;
    }
    table.defined_sizes .cell_2-2 {
      width: 100px;
    }
    table .row_3 {
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button class="toggle_3rd_row">Toggle third row</button>
    <button class="toggle_widths">Toggle cell widths in CSS</button>
    <table border="1" cellpadding="0" cellspacing="20">
      <caption>Why do the cells only size properly with the colspan-less third row present??</caption>
      <tr>
        <td class="cell_1-1">
    
          <img src="http://placehold.it/100x100?text=100w">
    
        </td>
    
        <td colspan="2" class="cell_1-2">
    
          <img src="http://placehold.it/222x100?text=222w">
    
        </td>
      </tr>
      <tr>
        <td colspan="2" class="cell_2-1">
    
          <img src="http://placehold.it/222x100?text=222w">
    
        </td>
        <td class="cell_2-2">
    
          <img src="http://placehold.it/100x100?text=100w">
    
        </td>
      </tr>
      <tr class="row_3">
        <td>
          <img src="http://placehold.it/100x100?text=100w">
        </td>
        <td>
          <img src="http://placehold.it/100x100?text=100w">
        </td>
        <td>
          <img src="http://placehold.it/100x100?text=100w">
        </td>
      </tr>
    </table>

    【讨论】:

      猜你喜欢
      • 2014-01-03
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-10
      • 2012-06-25
      相关资源
      最近更新 更多