CSS3 selectors




Introduction

All the CSS3 selectors, which will be discussed in the article are supported by browsers Firefox3.5 , Chrome, Safari, Opera12 (webkit). About support for Internet Explorer will be listed separately.

 

Main

  • * — any element (IE6 )
  • div — elements with the same tag (IE6 )
  • #id — element with a given id (IE6 )
  • .class — element with that class (IE6 )
  • [name="value"] selectors on the attribute
  • :visited "pseudo — classes", the rest of the different conditions on the element

Selectors can be combined by recording in sequence, without spaces:

  • .c1.c2 — elements simultaneously with two classes c1 and c2 (IE6 )
  • a#id.c1.c2:visited element a with the given id, classes c1 and c2, and the pseudo-class visited (IE6 )

Relationship

  • div p elements pthat are children of div (IE6 )
  • div > p only the direct descendants (IE7 )
  • div ~ p — right neighbors: all p at the same nesting level that come after the div (IE7 )
  • div p — first right neighbor: p at the same nesting level that goes right after the div (if any) (IE7 )

 

Filter by neighbours (IE9 )

  • :first-child is the first child of its parent
  • :last-child — last child of its parent
  • :only-child is the only child of its parent, neighboring elements are no
  • :nth-child(a) — child room a his parents, for example :nth-child(2) — second descendant of. Numbering starts with 1
  • :nth-child(an b) — extension of the previous selector by specifying the numbers of the descendant formula, where a,b are constants, and n means any integer

Filters the elements which fall under the formula at any n. For example:

  • :nth-child(2n) selects the items number 2, 4, 6..., that is even
  • :nth-child(2n 1) select elements number 1, 3..., that is odd
  • :nth-child(3n 2) selects the items number 2, 5, 8 and so on
  • :nth-last-child(a), :nth-last-child(an b) is the same, but the count starts from the end, e.g. :nth-last-child(2) — the second element from the end

 

Filter the neighbors with the same tag (IE9 )

  • :first-of-type — first element of the same type
  • :last-of-type last element of the same type
  • :only-of-type — all elements of the same type
  • :nth-of-type(a) element number (n) of the same type
  • :nth-last-of-type(n) — element number (n) of the same type, but the count starts from the end

 

Selectors by attribute tag (IE7 )

The attribute entirely

  • [attr] — attribute is set
  • [attr="val"] — attribute is equal to val

At the beginning of the attribute

  • [attr^="val"] — attribute starts with val, e.g. "value"
  • [attr|="val"] — attribute equals val or begins with val-, for example equal to "val-1"

The content

  • [attr*="val"] — attribute contains the substring val, for example equal to "myvalue"
  • [attr~="val"] — attribute contains val as one of the values separated by a space. For example: [attr~="delete"] is true of "edit delete" and false to "undelete" or "no-delete"

At the end of the attribute

  • [attr$="val"] — attribute ends with val, for example equal to "myval"

 

Other pseudo-classes

  • :not(selector) — all matching except the selector, including pseudo-classes, for example: :not(:hover)— select all, except those that are under the mouse (IE9 )
  • :focus — in focus (IE8 )
  • :hover — mouse (IE8 )
  • :empty — no children (even without text) (IE9 )
  • :checked, :disabled, :enabled — state INPUT (IE9 )
  • :target — filter will work for the item ID which coincides with the anchor #... current URL (IE9 )
  • :first-letter filter will work for the first character (IE6 )
  • :first-line — filter works for the first line of text (IE6 )

For example, if the page has an element with id="intro", the rule :target { color: red } will highlight it in that case, if the current URL has the form http://...#intro

 

Pseudo-elements :before, :after (IE8 )

The key is the CSS contentwithout pseudo-element will not be created.

  1. span:before {
  2. content: "";
  3. }
  4. span:after {
  5. content: "";
  6. }

 

Features

All modern browsers support the selectors using :: (double colon), but EI6 can not do it. So if you need support for older browsers should be written using a single colon.

Live demo
Download ZIP







Found comments - 14






Козлов Андрей December 30, 2016
Как развивать то? Про JS писать не хочу, а про CSS и так много написано. Это единственная статья на сайте, которая простенькая. Сам ей частенько пользуюсь, когда хитрые селекторы забываю.... :)
Другой Артём June 10, 2016
Очень хорошая шпора по селекторам. В начале пути - полезная статья. Зря забросил сайт. Развивал бы...
Илья May 11, 2016
Отличная статья. Помогла!
Vampireos April 27, 2016
Классные статьи и очень понятно разъясняешь принципы^ ^
Козлов Андрей February 08, 2016
Не реализовывал я такую возможность, потому как сайт был создан для узкого круга специалистов (можете посмотреть по счетчику количества уникальных посетителей в футере) коих не так много как хотелось бы. :-( А также для моих студентов. Я преподаю курс web-разработки в Томском Унивеситете Систем Управления и Радиоэлектроники (ТУСУР).
Катерина February 06, 2016
Зачётный сайт! =) У вас есть регистрация, чтобы "мыло" привязать к сайту?
Козлов Андрей October 30, 2015
Да, но не всегда. В вашем случае это будет выглядеть примерно так http://jsfiddle.net/cdpy48pp/1/ Я там много "бантиков" добавил, чтобы нормально смотрелось. Ну думаю поймете принцип. :-)
Максим October 30, 2015
А есть возможность как-то менять элементы родителя из-под потомка? Например, у меня внутри div лежит checkbox. При активировании checkbox можно ли к div добавить, например, рамки?
Козлов Андрей September 25, 2015
Спасибо, я старался :)
Игорь September 21, 2015
Крутой сайт, однозначно, и доступно все поясняется. Автору зачет! :)
qeweqwe August 22, 2015
;-}
мачсмсч July 30, 2015
:x
Козлов Андрей July 07, 2015
Да, на этом сайте нет JS и кастомизация смайла сделана тоже на CSS. Думаю написать пару новых статей. Может у кого будут пожелания на какую тему? :}
Артем June 29, 2015
Как я понял аватар я могу сам для себя любой сляпать? :-0
Хахахаха, прикол... :-)
Current text is converted to a smiley
:) :( :0 :@ :# :$ :? :] :[ :} :{ :k :p :x :| :Q :O :S :D :X :C :-) :-( :-0 :-# :-$ :-? :-] :-[ :-} :-{ :-o :-p :-x :-| :-Q :-O :-S :-D :-X :-C :-* :-r :-t :-i :-s :-j :-k :-l :-z :-\ :-/ :-I :-J :-K :-L :-Z ;) ;] ;} ;-) ;-] ;-} =) =( =0 =@ =# =$ =? =] =[ =} ={ =o =p =x =| =Q =O =S =D =X =C
:)

Designer avatar

Gender
Hairs/Hats Mouth
Eyes Glasses
Result