表格单元格上的重叠colspan可以缩小到适合吗?

时间:2017-02-04 12:01:10

标签: html html-table sizing

对于我的生活,我无法想到这一点。拿一张有2行的表,每行有2个单元格。右上角和左下角的单元格设置为colspan="2"(因此表格确实有3列)。如果非colspan单元格内部有100×100图像,并且colspan单元格有200×100图像,那么您希望表格宽度大约为300,对吗?不,不,不!它更像是400。

请参阅此笔:http://codepen.io/sandwich/pen/apYPdL

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

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

1 个答案:

答案 0 :(得分:0)

  

如果非colspan单元格内部有100×100图像,并且colspan单元格中有200×100图像,那么您希望表格宽度大约为300,对吗?

好吧,如果<table>border-collapse:collapse,但因为它是separate和20px左右边框,那么对于2列来说,这是80px额外的。这至少是380px。

尝试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>