代码之家  ›  专栏  ›  技术社区  ›  thk

根据单元格大小的灵活表格

  •  0
  • thk  · 技术社区  · 6 年前

    我有这样的桌子:

       ------------------------------------------------
      |   product-name                   | icon | text |
       ------------------------------------------------
      |   product-info                   | icon | text |
       ------------------------------------------------
    

    我希望我的单元格根据上一个单元格内容灵活:

       ------------------------------------------------
      |   product-name                      | ic | smt |
       ------------------------------------------------
      |   product-info                      | ic | smt |
       ------------------------------------------------
    
       -------------------------------------------------
      |   product-name                | icon | big-text |
       -------------------------------------------------
      |   product-info, bla bla bla...| icon | text     |
       -------------------------------------------------
    

    我试过这个CSS:

      table {
        table-layout: fixed;
        font-size: 12px;
        width: 100%;
      }
    
      table td:nth-child(1) {
        max-width: 70%;
      }
    
      table td:nth-child(2) {
        width: 10%;
      }
    
      table td:nth-child(3) {
        max-width: 20%;
      }
    

    我放 table-layout:fixed 但是我不能让最大宽度工作。我不知道如何判断最后一个单元格是决定其他单元格大小的单元格。

    这个 product-info 内容可以很大,我应用了一个省略号,它变得太大了。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Mr Lister hawi    6 年前

    首先要做的是摆脱 table-layout: fixed 因为这与你想要的正好相反。对于其他的,如果你想要桌子有弹性,不要试图强迫它们的宽度!

    有一个小技巧可以使一些表格单元格与内容一样宽,同时给其余单元格剩余的空间:使其宽度 1px 并确保它们不能通过设置进行包装 white-space: nowrap . 剩下的就自然了。

    table {
      border: 1px outset;
      width: 100%;
    }
    
    th, td {
      border: 1px inset;
    }
    
    table td:nth-child(2),
    table td:nth-child(3) {
      white-space:nowrap;
      width: 1px;
    }
    <table>
      <tr>
        <td>product-name</td>
        <td>ic</td>
        <td>smt</td>
      </tr>
      <tr>
        <td>product-info</td>
        <td>ic</td>
        <td>smt</td>
      </tr>
    </table>
    <br>
    <table>
      <tr>
        <td>product-name</td>
        <td>icon</td>
        <td>big-text</td>
      </tr>
      <tr>
        <td>product-info, bla bla bla...</td>
        <td>ic</td>
        <td>smt</td>
      </tr>
    </table>

    希望这就是你的意思!