-3

我如何定位一些子元素,除非父元素是其父元素的第一个或最后一个子元素?

请参阅我的 CSS 中的注释以更好地理解我的意思。

CSS:

/* Always apply */
tr th, tr td
{
    text-align: left;
    vertical-align: top;
}

/* Apply to all except first <tr> */
tr th, tr td
{
    padding-top: 5px;
}

/* Apply to all except last <tr> */
tr th, tr td
{
    border-bottom: 1px solid #c4c4c4;
    padding-bottom: 5px;
}

HTML:

<table>
    <tr>
        <th>Born</th>
        <td><time datetime="1986-11-05">5<sup>th</sup> November 1986</time></td>
    </tr>
    <tr>
        <th>Gender</th>
        <td>Male</td>
    </tr>
    <tr>
        <th>Sports</th>
        <td>Football<br />Tennis</td>
    </tr>
    <tr>
        <th>Teams</th>
        <td>Liverpool FC<br />Spain FC</td>
    </tr>
</table>
4

4 回答 4

7

好吧,您对链接的问题有一个解决方案。使用:not()伪类:

/* Apply to all except first <tr> */
tr:not(:first-child) th, tr:not(:first-child) td{
    padding-top: 5px;
}

/* Apply to all except last <tr> */
tr:not(:last-child) th, tr:not(:last-child) td{
    border-bottom: 1px solid #c4c4c4;
    padding-bottom: 5px;
}

小提琴

(虽然这在 IE 8 中不起作用)


IE 7+ 的替代方案,如果边框样式可以更改:

/* Apply to all */
tr th, tr td{
    border-top: 1px solid #c4c4c4;
    padding-top: 5px;
}

/* Remove styles from first */
tr:first-child th, tr:first-child td{
    border-top: 0;
    padding-top: 0;
}

或者

/* Apply to all but first */
tr + tr th, tr + tr td{
    border-top: 1px solid #c4c4c4;
    padding-top: 5px;
}

(但不确定+IE 7 是否支持)

于 2013-02-04T05:16:15.497 回答
1
tr th,
tr td
    {} /* always apply */

tr:first-child th,
tr:first-child td
    {} /* apply only to td and th of the first tr */

tr:last-child th,
tr:last-child td
    {} /* apply only to td and th of the last tr */
于 2013-02-04T05:07:42.350 回答
1

你可以通过这样做来实现这一点

tr:not(:first-child) th, tr:not(:first-child) td{
 padding-top:5px;
}
tr:not(:last-child) th, tr:not(:last-child) td{
 border-bottom: 1px solid #c4c4c4;
 padding-bottom: 5px;
}

您还可以为每个类的第一个和最后一个添加一个类,可能类似于firstthand lastth。这肯定是最简单的解决方案。它也被所有浏览器支持

此外,正如我们所说,您可以定义法线,然后为第一个和最后一个应用不同的样式,尽管这不是一种很好的完成方法

tr th, tr td{
 padding: 5px 0; /*I would combine the padding for top and bottom for a more condensed and semantically correct markup*/

 border-bottom: 1px solid #c4c4c4;
}
tr:first-child th, tr:first-child td{
 padding:top: 0;
}
tr:last-child th, tr:last-child td{
 border-bottom:0;
 padding-bottom:0
于 2013-02-04T05:09:56.990 回答
1
tr:first-child ~ tr:not(:last-child) td,
tr:first-child ~ tr:not(:last-child) th
    {background:red;}

这是你可以用兄弟组合器存档的最好的方法,但它不适用于旧浏览器,因为 :not 并且可能还有 ~

于 2013-02-04T05:21:56.750 回答