首页 > 解决方案 > CSS:将宽度/高度设置为表格标题列的百分比减去像素

问题描述

为什么在下面的示例中,表格标题的列不采用 CSS 中定义的宽度?

我认为在表 1 中,浏览器无法计算一个百分比值和一个固定值。

/************* commun css***********************/
table {
   border-collapse: collapse;
   table-layout:fixed;
   width: 100%;
   position: relative;
}

td, th {
   border: 1px solid black;
   -webkit-box-sizing: border-box;
}

tr{
  width: 100%;
  position: relative;
}

/************* css table 1***********************/

.table1 .col1 {
  width: calc(35% - 10px);
}

.table1 .col2 {
  width: calc(40% - 10px);
}

.table1 .col3 {
  width: calc(25% - 10px);
}

.table1 .col4 {
  width: 30px;
}

/************* css table 2***********************/
.table2 .col1 {
  width: calc(30%);
}

.table2 .col2 {
  width: calc(20%);
}

.table2 .col3 {
  width: calc(50%);
}
<p>
Table 1 : invalid render (Chrome browser)
</p>
<table class="table1">
  <thead>
    <tr>
      <th class="col1">Col 1</th>
      <th class="col2">Col 2</th>
      <th class="col3">Col 3</th>
      <th class="col4">Col 4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Row 1</td>
      <td>Row 1</td>
      <td>Row 1</td>
      <td>Row 1</td>
    </tr>
    <tr>
      <td>Row 2</td>
      <td>Row 2</td>
      <td>Row 2</td>
      <td>Row 2</td>
    </tr>
  </tbody>
</table>

<p>
Table 2 : valid render (Chrome browser)
</p>

<table class="table2">
  <thead>
    <tr>
      <th class="col1">Col 1</th>
      <th class="col2">Col 2</th>
      <th class="col3">Col 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Row 1</td>
      <td>Row 1</td>
      <td>Row 1</td>
    </tr>
    <tr>
      <td>Row 2</td>
      <td>Row 2</td>
      <td>Row 2</td>
    </tr>
  </tbody>
</table>

在这种情况下有人有什么建议吗?

先感谢您

示例:https ://jsfiddle.net/3wq65hb4/

标签: csswidthpixelcalctablecell

解决方案


是的,表格的 calc() 宽度存在问题。但它适用于div。在 div 而不是表格上制作它怎么样?

让我们看一下示例: https ://jsfiddle.net/3wq65hb4/39/

你可以在那里找到:

.row {
    display: flex;
}

它适用于列的相同高度。你也可以在那里找到:

margin-left: -1px;

这是边界的解决方案 - 避免双重边界,如:

双列宽

还要记住你的列的 max-width: 30px 意味着它总是 30px 即使你的内容会更宽:

更宽的柱子

但也许这是你想要达到的。

让我知道该解决方案是否适合您。祝其他 html 好运 :)


推荐阅读