cssが指定されてない文字を消すcss

Geminiに次のように尋ねた。

次のようなhtml構造で「文字4」だけを隠すcssは可能ですか?

<td class=”author column-author” data-colname=”投稿者”><strong><img > 文字1</strong><br><a href=”” rel=”noopener noreferrer”>文字2</a><br><a href=””>文字3</a><br><a href=””>文字4</a></td>

Geminiの回答。

  1. nth-childセレクタを使用する方法
    この方法は、「文字4」が常に同じ位置にある場合に有効です。
    CSS
    .author.column-author a:nth-child(3) { /* 文字4は3番目のaタグ */
    display: none;
    }
    利点: シンプルで直接的です。
    注意点: HTMLの構造が変更された場合(例えば、別のリンクが追加された場合)に、意図しない要素が非表示になる可能性があります。
  2. last-childセレクタを使用する方法
    もし「文字4」が常に最後の a タグである場合は、この方法が使えます。
    CSS
    .author.column-author a:last-child {
    display: none;
    }
    利点: HTMLの構造が多少変更されても、最後の a タグを確実に非表示にできます。
    注意点: 「文字4」が最後の a タグでない場合は機能しません。

他の方法も教わったが「2.last-childセレクタを使用する方法」で消せた。しかし、新たなニーズが生じた。

.author.column-author a:last-child {
display: none;
}
の一つ上も消す必要が生じました。どうしたら良いですか?

Geminiの回答(抜粋)。

.author.column-author a:last-child,
.author.column-author a:nth-last-child(2) {
display: none;
}

消えなかった。

a:nth-last-child(2)は効かないようです。
.author.column-author a:nth-child(3)をやったら文字2が消えました。

Geminiはその理由を答えられなかったが、私が次のコードを試したら文字3と文字4が消えた。

.author.column-author a:nth-child(5),
.author.column-author a:nth-child(7){
display: none;
}

Geminiは次のように答えた。

提示されたCSSコード
.author.column-author a:nth-child(5),
.author.column-author a:nth-child(7) {
display: none;
}
は、.author.column-author 要素内の5番目と7番目の a 要素を非表示にするものです。
このコードで問題が解決したのであれば、そのまま使用していただいて構いません。

私は尋ねた。

どうして数字を一つ置きにしたら文字が消えたのでしょう?

ここでようやく正答が出てきた。

要するに、最初の回答「nth-childセレクタを使用する方法」の「.author.column-author a:nth-child(3) { /* 文字4は3番目のaタグ */」は「3番目のaタグ」だから「a:nth-child(3) 」と回答したらしい。正しくは、

1. <strong><img > 文字1</strong>
2. <br>
3. <a href="" rel="noopener noreferrer">文字2</a>
4. <br>
5. <a href="">文字3</a>
6. <br>
7. <a href="">文字4</a>

の5.と7.を消したいから

.author.column-author a:nth-child(5),
.author.column-author a:nth-child(7){
display: none;
}

となり、それらがaタグで無かったら「display: none;」をしないということらしい。

:nth-child() – CSS: カスケーディングスタイルシート | MDN
https://developer.mozilla.org/ja/docs/Web/CSS/:nth-child

コメント

タイトルとURLをコピーしました