-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: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;
}

それぞれの最初と最後に 1 つのクラスを追加することもできます。おそらく と のようなものfirstthです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;}

これは siblings コンビネータでアーカイブできる最良のものですが、:not とおそらく ~ のため、古いブラウザでは動作しません。

于 2013-02-04T05:21:56.750 に答える
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 に答える