:nth-last-of-type() в CSS — n-й елемент типу з кінця
автор: NagarD
Загальний опис
автор: NagarD
Синтаксис
:nth-last-of-type(number) {
css declarations;
}
Переглядачі
| Переглядач | ||||||
|---|---|---|---|---|---|---|
| 4 | 3.5 | 3.1 | 9.5 | 12 | 9 |
| Переглядач | ||||
|---|---|---|---|---|
| 2 | 18 | 4 | 2 |
Приклади
+ запропонувати свій приклад у пісочниці
Один список, п’ять правил і підписи прямо в рядках: видно, що :nth-last-of-type рахує лише абзаци й лише з кінця, що клас у лічбі не бере участі зовсім, чим від нього відрізняється :nth-last-child і як сучасна форма 1 of .note робить те, чого від of-type чекали.
HTML
<div class="box">
<p class="note">абзац 1, клас note</p>
<p class="note">абзац 2, клас note</p>
<div class="other">не абзац — div між ними</div>
<p class="plain">абзац 3, клас plain</p>
<p class="plain">абзац 4, клас plain</p>
<div class="other">не абзац — останній елемент у блоці</div>
</div>
<ul class="legend">
<li><b class="s1">синя рамка</b> — p:nth-last-of-type(1): останній абзац</li>
<li><b class="s2">зелений фон</b> — p:nth-last-of-type(-n+3): три останні абзаци</li>
<li><b class="s3">червона рамка</b> — :nth-last-child(1): остання дитина, і це div</li>
<li><b class="s4">жовта смуга</b> — :nth-last-child(1 of .note): останній серед note</li>
<li>а <code>p.note:nth-last-of-type(1)</code> не підсвітив нічого: останній
абзац має клас plain, тож умова не збіглася</li>
</ul>
CSS
.box {
max-width: 520px;
padding: 10px 14px;
border: 1px solid #b9c6d8;
border-radius: 6px;
}
.box p,
.box .other {
margin: 6px 0;
padding: 6px 10px;
border: 3px solid transparent;
border-radius: 4px;
background: #f4f6fa;
}
.box .other {
color: #5a6472;
font-style: italic;
}
/* останній абзац — рахуються ЛИШЕ абзаци */
.box p:nth-last-of-type(1) {
border-color: #2f6fd0;
}
/* три останні абзаци */
.box p:nth-last-of-type(-n+3) {
background: #edf9ef;
}
/* остання дитина взагалі — і це div, а не абзац */
.box :nth-last-child(1) {
border-color: #d64545;
}
/* сучасна форма: останній СЕРЕД тих, хто має клас note */
.box :nth-last-child(1 of .note) {
border-left: 12px solid #f2b134;
}
/* а ось це правило не спрацює жодного разу */
.box p.note:nth-last-of-type(1) {
outline: 4px solid #000;
}
.legend {
max-width: 560px;
margin-top: 14px;
padding-left: 20px;
color: #5a6472;
font-size: .9em;
}
.legend li {
margin: 4px 0;
}
.legend b {
color: #111;
}
code {
background: #eef4ff;
border-radius: 3px;
padding: 0 4px;
}
Лічба з кінця і тільки серед абзаців: footer наприкінці не рахується, тож червоним стає середній p.
HTML
<div>
<p>Перший абзац.</p>
<p>Другий з кінця серед p — червоний.</p>
<p>Останній абзац.</p>
<footer>footer не рахується: лічба лише по абзацах.</footer>
</div>
CSS
p:nth-last-of-type(2) {
background: red;
}
Коментарі
Коментарів ще немає — будьте першим!