首页 > 解决方案 > 用'table-layout:fixed;'控制表格单元格(td)的宽度 不管用

问题描述

在下面的代码中,我尝试使用以下方法控制列的宽度:

table-layout: fixed;

但它不起作用;

[class^="col--"] { 
float: left;
}

.col-7 {
  width: 35%;
}

.col-4 {
  width: 20%;
}

.col-3 {
  width: 15%;
}

.col-2 {
  width: 10%;
}


.at { 
background-color:green;
color: white;
width: calc(100% - 3rem);
}

table { 
  margin: 1.5rem 0 0;
  border-collapse: collapse;
  table-layout: fixed;
  width: 100%;
}

td { 
  overflow: hidden;
  padding: .5rem 0;
  float: none;
}
<div class="at">
  <table>
    <thead>
      <tr>
        <th>Row 1</th>
        <th>Row 2</th>
        <th>Row 3</th>
        <th>Row 5</th>
        <th>Row 6</th>
      </tr>
      </thead>
      <tbody>     
        <tr>
          <td class="col-7">Lorem ipsum albatros</td>
          <td class="col-4">#fdsafdsa</td>
          <td class="col-4">Jan. 15, 2019</td>
          <td class="col-2">Pending Action</td>
          <td class="col--3">Lorem ipsum Delete</td>
       </tr>
      </tbody>
   </table>
</div>

标签: css

解决方案


我的理解是,列的宽度将由表中的第一行决定,在这种情况下,在thead...如果你把类放在那里,它就可以工作。

[class^="col-"] {
  text-align: right;
  border: 1px solid red;
}

.col-7 {
  width: 35%;
}

.col-4 {
  width: 20%;
}

.col-3 {
  width: 15%;
}

.col-2 {
  width: 10%;
}

.at {
  background-color: green;
  color: white;
  width: calc(100% - 3rem);
}

table {
  margin: 1.5rem 0 0;
  border-collapse: collapse;
  table-layout: fixed;
  width: 100%;
}

td {
  overflow: hidden;
  padding: .5rem 0;
  float: none;
}
<div class="at">
  <table>
    <thead>
      <tr>
        <th class="col-7">Row 1</th>
        <th class="col-4">Row 2</th>
        <th class="col-4">Row 3</th>
        <th class="col-2">Row 5</th>
        <th class="col-3">Row 6</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="col-x">Lorem ipsum albatros</td>
        <td class="col-x">#fdsafdsa</td>
        <td class="col-x">Jan. 15, 2019</td>
        <td class="col-x">Pending Action</td>
        <td class="col-x">Lorem ipsum Delete</td>
      </tr>
    </tbody>
  </table>
</div>


推荐阅读