4

我想要一个 100 像素的表格,有 4 列,每列 25 像素。

那么当浏览器展开时,第一列最多可以变成50px。

有唯一的 CSS 解决方案吗?我真的很想避免使用 js 来设置这些样式。

HTML:

<table>
<tbody>
 <tr>
   <td>Item 1 expands</td>
   <td>Item 2</td>
   <td>Item 3</td>
   <td>Item 4</td>
 </tr>
</tbody>
</table>

CSS:

table {
  table-layout: fixed;
}

td {
  width: 25px;
}

td:nth-child(1) {
  ?? max-width: 500px; ??
  ?? width: 25%; ??
}
4

3 回答 3

3

To make the column expand smoothly instead of snapping into a new width with media queries:

table{ 
  max-width: 125px;
}
td{
   min-width: 25px;
}
td:nth-child(1){
   width:40%; // Translates to roughly 50px
}

This will allow the first column to expand with the available window space.

http://jsfiddle.net/RUNcm/

This works because if the table goes below 125px in width, the min-width of td kicks in and keeps the first child from going below 25px.

On the other hand, if the table is larger than 100px in width (because the user expanded the browser window), 40% width will allow it to go up to 52px but no further. (that's what max-width 125px; helps moderate).

Note on nth-child: As Jay Na stated, nth-child has less browser support than first-child. You might want to look into using the first-child pseudo-class instead.

MDN Docs

nth-child https://developer.mozilla.org/en-US/docs/CSS/:nth-child

first-child https://developer.mozilla.org/en-US/docs/CSS/:first-child

于 2013-04-23T19:29:27.727 回答
-1

在要修复的 TD 元素上设置 25px 的 with。从那时起,表格的宽度将定义第一列的宽度,因此您可以定义它是有意义的。

编辑例如:

table {
    max-width:575px;
}
td {
  width: 25px;
}

td:nth-child(1) {
width:auto;
}
于 2013-04-23T19:08:24.757 回答
-2

你会这样做:

@media all and (min-width:400px) { /* or whatever the threshold size is */
    td:first-child {width:50px}
}
于 2013-04-23T19:06:35.670 回答