为什么表格需要width:0来尊重列的宽度?

时间:2018-08-13 16:44:21

标签: html css css-tables

即使指定的列宽为50px和100px,此表的列宽也为59px和100px。

table {
  border-collapse: collapse;
  border-spacing: 0;
  table-layout: fixed;
}

col:first-child {
  width: 50px;
}

col:nth-child(2) {
  width: 100px;
}

td, th {
  border: 1px solid black;
}
<table>
  <colgroup>
    <col>
    <col>
  </colgroup>
  <thead>
    <tr>
      <th>Column A</th>
      <th>Column B</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
    </tr>
  </tbody>
</table>

但是如果我将width: 0添加到表中,它将起作用。

table {
  border-collapse: collapse;
  border-spacing: 0;
  table-layout: fixed;
  width: 0;
}

col:first-child {
  width: 50px;
}

col:nth-child(2) {
  width: 100px;
}

td, th {
  border: 1px solid black;
}
<table>
  <colgroup>
    <col>
    <col>
  </colgroup>
  <thead>
    <tr>
      <th>Column A</th>
      <th>Column B</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
    </tr>
  </tbody>
</table>

为什么需要设置width: 0?有更好的方法吗?>

3 个答案:

答案 0 :(得分:0)

您可以将public enum RequestResult { case success(JSONStandard) case failure(Error) } public func getAccessToken() { // Get new token let parameters = ["client_id" : clientID, "client_secret" : clientSecret, "grant_type" : "client_credentials"] func getAccessTokenClosure(completion: @escaping (RequestResult) -> ()) { Alamofire.request("https://accounts.spotify.com/api/token", method: .post, parameters: parameters).responseJSON(completionHandler: { response in // Check if response is valid if let accessToken = response.result.value as? JSONStandard { completion(.success(accessToken)) } else { completion(.failure(_)) // Can fail with a custom error } }) } getAccessTokenClosure { result in switch result { case .success(let token): // Success case .failure(_): // Failed, could be due to internet issues etc. } } } 属性设置为max-width元素。另外,您需要指定<th>box-sizing: border-box;<th>元素以包括填充和边框

<td>
table {
  border-collapse: collapse;
  border-spacing: 0;
  table-layout: fixed;
}

th:first-child {
  max-width: 50px;
  width: 50px;
}

th:nth-child(2) {
  max-width: 100px;
  width: 100px;
}

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

答案 1 :(得分:0)

CSS 2.2 Section 17.5.2.1 Fixed table layout说:

  

可以通过'width'属性显式指定表格的宽度。值“ auto”(对于“ display:table”和“ display:inline-table”都适用)表示使用自动表格布局算法。

Width的初始值为auto,而用户代理样式表的确将其更改为表格元素。因此,尽管css为table-layout: fixed,但仍使用自动表布局算法,而不使用固定表布局算法。将宽度设置为其他值将强制使用固定表布局算法。

没有明显的“更好”的解决方案。


¹然后继续说,浏览器没有没有做到这一点,但看来他们仍然可以做到

答案 2 :(得分:-1)

也许您可以看看word-break

table {
  border-collapse: collapse;
  border-spacing: 0;
  table-layout: fixed;
}

col:first-child {
  width: 50px;
}

col:nth-child(2) {
  width: 100px;
}

td, th {
  border: 1px solid black;
  word-break:break-word;
}
<table>
  <colgroup>
    <col>
    <col>
  </colgroup>
  <thead>
    <tr>
      <th>Column A</th>
      <th>Column B</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
    </tr>
  </tbody>
</table>