Last child of div css

CSS :last-child Pseudo Class

The CSS :last-child pseudo-class selects the element if it is the last child among the other elements.

The :last-of-type selector can be used if the user wants to select and apply the style on the last paragraph whether or not it is the last child.

Originally the selected element had to have a parent. In Selectors Level 4, this is no longer required.

Version

Syntax

Example of the :last-child selector:

html> html> head> title>Title of the document title> style> p:last-child < background-color: #1c87c9; color: #ffffff; > style> head> body> h2>Last-child selector example h2> p>Lorem ipsum is simply dummy text. p> p>Lorem Ipsum is simply dummy text. p> body> html>

Example of the last child of the tag:

html> html> head> title>Title of the document title> style> li:last-child < background: #1c87c9; > style> head> body> h2>:last-child selector example h2> ul> li>Paris li> li>Moscow li> li>Rome li> ul> ol> li>Paris li> li>Moscow li> li>Rome li> ol> body> html>

Example of the last child of the tag:

html> html> head> title>Title of the document title> style> p:last-child < background: #8ebf42; > style> head> body> h2>:last-child selector example h2> p>Paragraph 1 p> p>Paragraph 2 p> p>Paragraph 3 p> p>Paragraph 4 p> body> html>

Example of :last-child for HTML lists:

html> html> head> style> ul li < color: #8ebf42; > ul li:last-child < border: 1px dotted #8ebf42; color: #1c87c9; > style> head> body> h2>:last-child selector example h2> ul> li>List Item 1 li> li>List Item 2 li> li> List Item 3 ul> li>List Item 3.1 li> li>List Item 3.2 li> li>List Item 3.3 li> ul> li> ul> body> html>

Browser support

Practice Your Knowledge

The :last-child CSS pseudo-class selects the element

if it is the last child among the other elements. based on their index starting from the last element upwards. if it is the only child of its parent.

Читайте также:  Php перенос строки консоль

Источник

CSS :last-child Selector

Specify a background color for the

element that is the last child of its parent:

Definition and Usage

The :last-child selector matches every element that is the last child of its parent.

Tip: p:last-child is equal to p:nth-last-child(1).

Browser Support

The numbers in the table specifies the first browser version that fully supports the selector.

CSS Syntax

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

:last-child

The :last-child CSS pseudo-class represents the last element among a group of sibling elements.

Try it

Syntax

Examples

Basic example

HTML

div> p>This text isn't selected.p> p>This text is selected!p> div> div> p>This text isn't selected.p> h2>This text isn't selected: it's not a `p`.h2> div> 

CSS

p:last-child  color: lime; background-color: black; padding: 5px; > 

Result

Styling a list

HTML

ul> li>Item 1li> li>Item 2li> li> Item 3 ul> li>Item 3.1li> li>Item 3.2li> li>Item 3.3li> ul> li> ul> 

CSS

ul li  color: blue; > ul li:last-child  border: 1px solid red; color: red; > 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Feb 21, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Псевдокласс :last-child

Псевдокласс :last-child задаёт стиль последнего элемента в группе братских элементов (имеющих одного родителя).

В качестве примера рассмотрим следующий код HTML:

 

Роль цитокинов при дорсалгии

Автор: Гордон Фримен, канд. физ.-мат. наук

Содержание статьи

Почта: freemen@blackmesa.com

Опубликовано:

Псевдокласс :last-child без указания селектора выберет все последние элементы внутри и установит для них красный цвет текста. Здесь последними идут

и они и будут выбраны.

При добавлении селектора к :last-child сперва берётся последний элемент, затем смотрится какого он типа. Если элемент совпадает с указанным селектором, то он будет выбран. Таким образом, выбирается элемент, если он удовлетворяет двум условиям одновременно: это последний элемент и это элемент указанного типа. Здесь красным цветом будет выделен абзац, поскольку последним идёт именно

.

Если вместо p использовать другой селектор, то ничего выбрано не будет, поскольку не выполняется условие «последний элемент это ».

Для выбора последнего элемента определённого типа используйте псевдокласс :last-of-type.

Вместо :last-child допустимо использовать :nth-last-child(1).

Синтаксис

Синтаксис

Описание Пример
Указывает тип значения.
A && B Значения должны выводиться в указанном порядке. &&
A | B Указывает, что надо выбрать только одно значение из предложенных (A или B). normal | small-caps
A || B Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. width || count
[ ] Группирует значения. [ crop || cross ]
* Повторять ноль или больше раз. [,]*
+ Повторять один или больше раз. +
? Указанный тип, слово или группа не является обязательным. inset?
Повторять не менее A, но не более B раз.
# Повторять один или больше раз через запятую. #

Пример

Результат примера показан на рис. 1. В данном примере псевдокласс :last-child применяется для определения стиля последнего элемента , расположенного внутри контейнера с именем класса block . Это позволило создать цветную полосу внизу блока без включения новых классов.

Результат использования псевдокласса :last-child

Рис. 1. Результат использования псевдокласса :last-child

Спецификация

Каждая спецификация проходит несколько стадий одобрения.

  • Recommendation ( Рекомендация ) — спецификация одобрена W3C и рекомендована как стандарт.
  • Candidate Recommendation ( Возможная рекомендация ) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта.
  • Proposed Recommendation ( Предлагаемая рекомендация ) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения.
  • Working Draft ( Рабочий проект ) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом.
  • Editor’s draft ( Редакторский черновик ) — черновая версия стандарта после внесения правок редакторами проекта.
  • Draft ( Черновик спецификации ) — первая черновая версия стандарта.

Браузеры

В таблице браузеров применяются следующие обозначения.

  • — элемент полностью поддерживается браузером;
  • — элемент браузером не воспринимается и игнорируется;
  • — при работе возможно появление различных ошибок, либо элемент поддерживается с оговорками.

Число указывает версию браузреа, начиная с которой элемент поддерживается.

См. также

Источник

Оцените статью