1. ホーム
  2. html

Changing CSS for last <li>

2023-09-10 06:33:17

Question

I am wondering if there is some way to change a CSS attribute for the last li in a list using CSS. I have looked into using :last-child , but this seems really buggy and I can't get it to work for me. I will use JavaScript to do this if necessary, but I want to know if anyone can think up a solution in CSS.

How to solved?

:last-child is really the only way to do it without modifying the HTML - but assuming you can do that, the main option is just to give it a class="last-item" , then do:

li.last-item { /* ... */ }

Obviously, you can automate this in the dynamic page generation language of your choice. Also, there is a lastChild という JavaScript プロパティが W3C DOM にあります。

でやりたいことをやる例です。 プロトタイプ :

$$("ul").each(function(x) { $(x.lastChild).addClassName("last-item"); });

あるいはもっとシンプルに

$$("ul li:last-child").each(function(x) { x.addClassName("last-item"); });

jQuery であれば、さらにコンパクトに書くことができます。

$("ul li:last-child").addClass("last-item");

また、この が必要です。 を使わなくても動作します。 last-child CSS セレクタを使用せずに動作します - むしろ、JavaScript の実装が使用されます - そのため、バグが少なく、ブラウザ間でより信頼できるはずです。