Select every second css selector. Events (selectors, behaviors) CSS. Pseudo-elements generated content

💖 Do you like it? Share the link with your friends

Not all, but more than enough

People who learn XHTML, as well as CSS from books, often find that CSS events are not fully described. In particular, only events such as hover, active, visited. There are many more CSS events and the possibilities they provide are very large.

Not shown here full list events, but only those that are really needed by a modern web designer.

If you assign an after event to a block, the generated code defined in the style sheet will be output after the block. To define the code, the CSS command is used - content, the syntax of which is content: "XHTML code".

Those. the whole command might look like this:
#someId:after
(content:"XHTML code") :before Works the same as after, but outputs the code before the element: first-child Sets the style for the first child of some other element.

Let's say that by applying this event to the h1 tag, the first and only the first level 1 heading will be rendered with the appropriate style. It is especially effective to use this event for styles of nested tags (multi-level), for example, like this:

body ol li:first-child(...)(i.e. In all ol lists, the first li element, but not the ul, will be displayed with the given styling settings)

:last-child Styles the last child of some other element. :focus Sets the style for form elements that receive focus, i.e. the ones you click on. For example, you can make the active text input field different from the inactive text input field. :hover Style for the element being hovered over. Can be used with all blocks and text (previously we only considered links). :lang( x) Assigns an element to a specific language without changing the content of the element in any way. This tag can be used, for example, to highlight links to various sources. Instead of x a two-digit international designation of the language is placed, or in other words, the name domain zone. For example, for Russia it is ru, for America us, and so on. If an element needs to define multiple languages ​​at once, they must be separated by a hyphen without spaces (in order of descending importance of the styles that each language defines). :visited Sets the style of a visited link:nth-child(x) Sets the style for specific elements or one specific element. x can be expressed:

  • number. In this case, only 1 element will be selected
  • expressions odd(all odd elements) or even(all even elements).
  • expression an+b, where n does not change, a and b are arbitrary numbers. For example, 7n+4. All elements that give a remainder of 4 when divided by 7 will be selected (4, 11, 18, etc.) In this case, if a or b are equal to 0, then they can be omitted. The n elements are counted from 0 to n-1
Attention! This behavior (selector) is only in the new CSS 3 standard and is only supported by modern browsers. :nth-last-child(x) Same as nth-child(x), but counts from the last n-1 element to 0. :emply Adds a style to an element that has no children, i.e. to an empty tag. :enabled Style for the selected, checked form element. Only for button, input, optgroup, option, select, textarea elements. This and the two subsequent selectors are only available in CSS 3:disabled Same as enabled, but for non-activated form elements:checked Only for radio and checkbox. Sets the style for the selected elements. :first-letter Sets the style for the first letter in the text (the so-called drop cap). Only commands supported CSS styling, but not markings. :first-line The same, but for the first line of text.

Deep dive into CSS selectors

The materials described above will be enough for many, but not for everyone. On the websites of large companies, public projects, social networks very complex CSS selectors are used and sometimes the functionality described above is not enough. Additionally, CSS must interact with server-side programming languages, i.e. Often CSS for certain pages is automatically generated. At the same time, it must function correctly and correctly.

We mentioned the heredity of elements. Now we will analyze it in more depth.

CSS can define rules for various types heredity, or the belonging of elements to a parent element. All of them serve only to select elements to which the rule will be applied.

Combinators (creating a connection between styles based on heredity)
Adjacent Sibling (+) This combinator defines 2 elements that immediately follow each other (there are no other elements between them with the same parent as those 2 elements, but there may be elements that inherit them) and have the same parent. The style is applied to both elements at once. Recording syntax (spaces are not included)
E+F(...)
where E is the first element, F is the second element. For example,
h1+h2(font-family:serif)
This entry will define the style only for successive h1 and h2 elements that have the same parent. If there is another h2 tag after h2, then the style is not applied to it.
Child (>) Combinator The combinator identifies all elements that are direct descendants of one element. Supports multiple levels of nesting, for example:
body > div > p(...)
That is, the style will only be applied to paragraphs that are children of all divs that directly belong to the body tag.
Descendant Defines an arbitrary connection between elements. That is, elements should not be direct descendants, but simply descendants of one element. Syntax(space required):
E F(...)
For example:
table.table1 td(...)
That is, the style will be defined in all descendant columns of the table with class table1, even if there are other tables within this table. The style will also be applied to the columns of the child tables.
General Sibling (~) Syntax E~F. The combinator performs the same function as Adjacent Sibling, except that between E and F there can be any number of elements of the same nesting level and there can be more than one F.
Attributes. Attribute selectors. Creating your own attributes
Equality [=] Each tag can have an attribute (for example, an id attribute, which almost any tag can have, or a width attribute (for blocks only)). You can create your own attribute, which is a text string. For example, attr. Creating your own attributes is useful for attribute selectors in CSS. Attributes can be used in conjunction with combinators.
Equality specifies the style for all elements whose specified attribute is exactly equal to the specified value. Syntax:
{...}
As you can see, no tags are defined here. Styles are defined for all elements that have the attribute att equal to the value val. Att and val can take identifier values ​​(for example, for att there can be any learned attributes, for val - none, block, etc.) and string values, i.e. just a word (for example, will define all elements with the entry<... attr="test" ...="">).
Existence Identifies all elements that have an attribute, regardless of its value. Syntax:
{...}
att - attribute (or string value, i.e. its own attribute)
Prefix [^=] Defines elements that have an att attribute that takes a value starting with val. Syntax:
{...}
att - attribute (or string value, i.e. its own attribute), val - attribute value
A very good example: Wikipedia. On this site, all links leading to sites other than Wikipedia have an icon (arrow) behind them. Here is an example recording that allows you to write this style:
:after(content" "}
Suffix [$=] Defines elements that have an att attribute that takes a value ending in val. Syntax
{...}
This attribute has recently begun to be used to put pictures in front of various links that will visually indicate to the user which file or page the link will send it to. For example, before links to PDF files you can put a PDF icon. Example:
:before(content:" "}
Substring [*=] Recording syntax:
{...}
Selects all elements with the att attribute whose value includes the substring val. For example, "54" is the substring "132 54 6", "val" - substring "value", etc.
Whitespace [~=] Whitespace is the same as Substring, however the substring must be a word, i.e. surrounded by spaces in the string.
Hyphen [|=] Same as Substring, except the substring must be part of the attribute and separated from the other part(s) by a hyphen. Example:
{...}
will select all tags with the lang attribute whose value contains en, for example en-ru, ru-de-en, etc.

This concludes the study of XHTML+CSS. Next lessons will be about JavaScript.

CSS (Cascading Style Sheets) is a style sheet language that allows you to attach style (such as fonts and color) to structured documents (such as HTML documents and XML applications). Typically, CSS styles are used to create and change the style of elements of web pages and user interfaces written in HTML languages and XHTML, but can also be applied to any kind of XML document, including XML, SVG and XUL. By separating document presentation style from document content, CSS makes it easier to create web pages and maintain sites.

CSS supports media-specific style sheets so authors can tailor the presentation of their documents to visual browsers, auditory devices, printers, braille devices, handheld devices, and more.

Cascading style sheets describe rules for formatting elements using properties and the allowed values ​​for those properties. For each element, you can use a limited set of properties; other properties will not have any effect on it.

A style declaration consists of two parts: selector And ads. In HTML, element names are case insensitive, so "h1" works the same as "H1". The declaration consists of two parts: the property name (for example, color) and the property value (grey). The selector tells the browser which element to format, and the declaration block (code in curly braces) lists the formatting commands - properties and their values.

Rice. 1. Ad structure

Although the example provided only attempts to affect a couple of properties needed to render an HTML document, it qualifies as a style sheet in its own right. When combined with other style sheets (one fundamental feature of CSS is that style sheets are combined), the rule will determine the final presentation of the document.

Types of cascading style sheets and their specifics

1. Types of style sheets

1.1. External style sheet

External style sheet represents text file with the .css extension, which contains a set of CSS styles for elements. The file is created in a code editor, just like an HTML page. The file can only contain styles, without HTML markup. An external style sheet is connected to a web page using a tag , located inside the section . These styles work for all pages of the site.

You can attach multiple style sheets to each web page by adding multiple tags in sequence , indicating the purpose of this style sheet in the media tag attribute. rel="stylesheet" specifies the type of link (link to a style sheet).

The type="text/css" attribute is not required by the HTML5 standard, so it can be omitted. If the attribute is missing, the default value is type="text/css" .

1.2. Internal styles

Internal styles embedded in a section HTML document and are defined inside the tag. Internal styles take precedence over external ones, but are inferior to inline styles (specified via the style attribute).

...

1.3. Built-in styles

When we write inline styles, we write the CSS code into the HTML file, directly inside the element tag using the style attribute:

Pay attention to this text.

Such styles only affect the element for which they are set.

1.4. @import rule

@import rule Allows you to load external style sheets. For the @import directive to work, it must appear in the style sheet (external or internal) before all other rules:

The @import rule is also used to include web fonts:

@import url(https://fonts.googleapis.com/css?family=Open+Sans&subset=latin,cyrillic);

2. Types of selectors

Selectors represent the structure of a web page. They help create rules for formatting web page elements. Selectors can be elements, their classes and identifiers, as well as pseudo-classes and pseudo-elements.

2.1. Universal selector

Matches any HTML element. For example, * (margin: 0;) will reset the margins for all site elements. The selector can also be used in combination with a pseudo-class or pseudo-element: *:after (CSS styles) , *:checked (CSS styles) .

2.2. Element selector

Element selectors allow you to format all elements of this type on all pages of the site. For example, h1 (font-family: Lobster, cursive;) will set the overall formatting style for all h1 headings.

2.3. Class selector

Class selectors allow you to specify styles for one or more elements with the same class name, placed in different places on the page or on different pages site. For example, to create a title with the headline class, you need to add the class attribute with the value headline to the opening tag

and set the style for the specified class. Styles created using a class can be applied to other elements, not necessarily of that type.

.headline ( text-transform: uppercase; color: lightblue; )

If an element has multiple class attributes, their values ​​are concatenated with spaces.

Instructions for using a personal computer

2.4. ID selector

The ID selector allows you to format one specific element. The id value must be unique, can appear only once on a single page, and must contain at least one character. The value must not contain spaces.

There are no other restrictions on what form id can take; in particular, identifiers can be all numbers, start with a number, start with an underscore, only have punctuation marks, etc.

An element's unique ID can be used for a variety of purposes, including as a way to refer to specific parts of a document using fragment IDs, as a way to target an element when scripting, and as a way to style a specific element from CSS.

#sidebar ( width: 300px; float: left; )

2.5. Descendant selector

Descendant selectors apply styles to elements within a container element. For example, ul li (text-transform: uppercase;) - will select all li elements that are children of all ul elements.

If you want to format the descendants of a particular element, you need to give that element a style class:

p.first a (color: green;) - this style will be applied to all links descendants of the paragraph with the first class;

p .first a (color: green;) - if you add a space, links located inside any .first class tag that is a child of the element will be styled

First a (color: green;) - this style will be applied to any link located inside another element, designated by the class.first .

2.6. Child selector

A child element is a direct child of its containing element. One element can have several child elements, but each element can have only one parent element. The child selector allows you to apply styles only if the child element comes immediately after the parent element and there are no other elements between them, that is, the child element is not nested within anything else.
For example, p > strong will select all strong elements that are children of the p element.

2.7. Sister selector

Sisterhood occurs between elements that share a common parent. Sibling selectors allow you to select elements from a group of elements of the same level.

h1 + p - will select all first paragraphs immediately following any tag

without affecting the remaining paragraphs;

h1 ~ p - will select all paragraphs that are sister to any h1 heading and immediately after it.

2.8. Attribute selector

Attribute selectors select elements based on the attribute name or attribute value:

[attribute] - all elements containing the specified attribute - all elements for which the alt attribute is specified;

selector[attribute] - elements of this type containing the specified attribute, img - only images for which the alt attribute is specified;

selector[attribute="value"] - elements of this type containing the specified attribute with a specific value, img - all pictures whose title contains the word flower;

selector[attribute~="value"] - elements partially containing a given value, for example, if several classes are specified for an element separated by a space, p - paragraphs whose class name contains feature ;

selector[attribute|="value"] - elements whose list of attribute values ​​begins with the specified word, p - paragraphs whose class name is feature or begins with feature ;

selector[attribute^="value"] - elements whose attribute value begins with the specified value, a - all links starting with http:// ;

selector[attribute$="value"] - elements whose attribute value ends with the specified value, img - all images in png format;

selector[attribute*="value"] - elements whose attribute value contains the specified word anywhere, a - all links whose name contains book .

2.9. Pseudo-class selector

Pseudo-classes are classes that are not actually attached to HTML tags. They allow you to apply CSS rules to elements when an event occurs or obeys a specific rule. Pseudo-classes characterize elements with the following properties:

:hover - any element over which the mouse cursor is hovered;

:focus - an interactive element that was navigated to using the keyboard or activated using the mouse;

:active - element that was activated by the user;

:valid - form fields whose contents have been checked in the browser for compliance with the specified data type;

:invalid — form fields whose contents do not match the specified data type;

:enabled - all active form fields;

:disabled — blocked form fields, i.e., in an inactive state;

:in-range - form fields whose values ​​are in the specified range;

:out-of-range - form fields whose values ​​are not within the specified range;

:lang() - elements with text in the specified language;

:not(selector) - elements that do not contain the specified selector - class, identifier, name or form field type - :not() ;

:target is an element with the # symbol that is referenced in the document;

:checked — selected (user-selected) form elements.

2.10. Structural pseudo-class selector

Structural pseudo-classes select child elements according to the parameter specified in parentheses:

:nth-child(odd) - odd child elements;

:nth-child(even) - even child elements;

:nth-child(3n) - every third element among children;

:nth-child(3n+2) - selects every third element, starting with the second child (+2) ;

:nth-child(n+2) - selects all elements starting from the second;

:nth-child(3) - selects the third child element;

:nth-last-child() - in the list of child elements, selects the element with the specified location, similar to :nth-child() , but starting from the last, in the opposite direction;

:first-child - allows you to style only the very first child element of the tag;

:last-child - allows you to format the last child element of the tag;

:only-child - selects an element that is the only child element;

:empty - selects elements that have no children;

:root - selects the element that is the root of the document - the html element.

2.11. Structural type pseudo-class selector

Indicates a specific type of child tag:

:nth-of-type() - selects elements similar to :nth-child() , but only takes into account the type of the element;

:first-of-type - selects the first child of a given type;

:last-of-type - selects the last element of this type;

:nth-last-of-type() - selects an element of the given type in a list of elements according to the specified location, starting from the end;

:only-of-type - selects a single element specified type among child elements parent element.

2.12. Pseudo element selector

Pseudo elements are used to add content, which is generated using the content property:

:first-letter - selects the first letter of each paragraph, applies only to block elements;

:first-line - selects the first line of element text, applies only to block elements;

:before - inserts generated content before the element;

:after - adds generated content after the element.

3. Selector combination

To more accurately select elements for formatting, you can use combinations of selectors:

img:nth-of-type(even) - will select all even pictures, alternative text which contains word css.

4. Grouping selectors

The same style can be applied to multiple elements at the same time. To do this, you need to list the required selectors on the left side of the declaration, separated by commas:

H1, h2, p, span ( color: tomato; background: white; )

5. Inheritance and cascade

Inheritance and cascade are two fundamental concepts in CSS that are closely related. Inheritance is where elements inherit properties from their parent (the element containing them). The cascade manifests itself in how different types style sheets are applied to a document, and how conflicting rules override each other.

5.1. Inheritance

Inheritance is the mechanism by which certain properties are transmitted from an ancestor to its descendants. The CSS specification allows for inheritance of properties related to the text content of the page, such as color, font, letter-spacing, line-height, list-style, text-align, text-indent, text-transform, visibility, white-space and word- spacing. In many cases, this is convenient because you don't have to set the font size and font family for every element on the web page.

Properties related to block formatting are not inherited. These are background , border , display , float and clear , height and width , margin , min-max-height and -width , outline , overflow , padding , position , text-decoration , vertical-align and z-index .

Forced inheritance

You can use the inherit keyword to force an element to inherit any property value of its parent element. This works even for properties that are not inherited by default.

How CSS styles are set and work

1) Styles can be inherited from the parent element (inherited properties or using the inherit value);

2) Styles located in the style sheet below override styles located in the table above;

3) Styles from different sources can be applied to one element. You can check which styles are applied in the browser developer mode. To do this, right-click on the element and select “View Code” (or something similar). The right column will list all the properties that are set on this element or inherited from a parent element, along with the style files in which they are specified, and the ordinal number of the line of code.


Rice. 2. Developer mode in Google browser Chrome

4) When defining a style, you can use any combination of selectors - an element selector, an element pseudo-class, a class or an element identifier.

div (border: 1px solid #eee;) #wrap (width: 500px;).box (float: left;).clear (clear: both;)

5.2. Cascade

Cascading is a mechanism that controls the final result in a situation where different CSS rules are applied to the same element. There are three criteria that determine the order in which properties are applied—the!important rule, specificity, and the order in which style sheets are included.

Rule!important

The weight of a rule can be specified using the!important keyword, which is added immediately after the property value, for example, span (font-weight: bold!important;) . The rule must be placed at the end of the declaration before the closing bracket, without a space. Such announcement will take precedence over all other rules. This rule allows you to cancel a property value and set a new one for an element from a group of elements in the case where there is no direct access to the style file.

Specificity

For each rule, the browser calculates selector specificity, and if an element has conflicting property declarations, the rule that has the most specificity is taken into account. The specificity value has four parts: 0, 0, 0, 0. The selector specificity is defined as follows:

for id, 0, 1, 0, 0 is added;
for class 0, 0, 1, 0 is added;
for each element and pseudo-element, 0, 0, 0, 1 is added;
for an inline style added directly to an element - 1, 0, 0, 0 ;
A universal selector has no specificity.

H1 (color: lightblue;) /*specificity 0, 0, 0, 1*/ em (color: silver;) /*specificity 0, 0, 0, 1*/ h1 em (color: gold;) /*specificity: 0, 0, 0, 1 + 0, 0, 0, 1 = 0, 0, 0, 2*/ div#main p.about (color: blue;) /*specificity: 0, 0, 0, 1 + 0 , 1, 0, 0 + 0, 0, 0, 1 + 0, 0, 1, 0 = 0, 1, 1, 2*/ .sidebar (color: grey;) /*specificity 0, 0, 1, 0 */ #sidebar (color: orange;) /*specificity 0, 1, 0, 0*/ li#sidebar (color: aqua;) /*specificity: 0, 0, 0, 1 + 0, 1, 0, 0 = 0, 1, 0, 1*/

As a result, those rules that are more specific will be applied to the element. For example, if an element has two specificities with values ​​0, 0, 0, 2 and 0, 1, 0, 1, then the second rule will win.

Order of connected tables

You can create multiple external style sheets and connect them to one web page. If in different tables will meet different meanings properties of one element, then as a result the rule in the style sheet listed below will be applied to the element.

CSS selectors define the elements to which a set of CSS rules apply.

Basic selectors

Universal selector Selects all elements. Optionally, it may be restricted to a specific namespace or to all namespaces.
Syntax:* ns |* *|*
Example:* will match all the elements of the document. Type selector Selects all elements that have the given node name.
Syntax: elementname
Example: input will match any element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent. "> element. Class selector Selects all elements that have the given class attribute.
Syntax:. classname
Example:.index will match any element that has a class of "index". ID selector Selects an element based on the value of its id attribute. There should be only one element with a given ID in a document.
Syntax:# idname
Example:#toc will match the element that has the ID "toc". Attribute selector Selects all elements that have the given attribute.
Syntax:[ attr ] [ attr = value ] [ attr ~= value ] [ attr |= value ] [ attr ^= value ] [ attr $= value ] [ attr *= value ]
Example: will match all elements that have the autoplay attribute set (to any value).

Grouping selectors

Selector list The , is a grouping method, it selects all the matching nodes.
Syntax: A, B
Example: div, span will match both and ) is the generic container for flow content. It has no effect on the content or layout until styled using CSS.">
elements.

Combinators

Descendant combinator The (space) combinator selects nodes that are descendants of the first element.
Syntax: A B
Example: div span will match all elements that are inside a ) is the generic container for flow content. It has no effect on the content or layout until styled using CSS.">
element. Child combinator The > combinator selects nodes that are direct children of the first element.
Syntax: A>B
Example: ul > li will match all element is used to represent an item in a list.">
  • elements that are nested directly inside a element represents an unordered list of items, typically rendered as a bulleted list.">
      element. General sibling combinator The ~ combinator selects siblings. This means that the second element follows the first (though not necessarily immediately), and both share the same parent.
      Syntax: A~B
      Example: p ~ span will match all elements that follow a element represents a paragraph.">

      , immediately or not. Adjacent sibling combinator The + combinator selects adjacent siblings. This means that the second element directly follows the first, and both share the same parent.
      Syntax: A+B
      Example: h2 + p will match all element represents a paragraph.">

      elements that directly follow an

      . Column combinator The || combinator selects nodes which belong to a column.
      Syntax: A || B
      Example: col || td will match all element defines a cell of a table that contains data. It participates in the table model."> elements that belong to the scope of the element defines a column within a table and is used for defining common semantics on all common cells. It is generally found within a element."> .

      Pseudo

      Pseudo classes The: pseudo allow the selection of elements based on state information that is not contained in the document tree.
      Example: a:visited will match all element (or anchor element), with its href attribute, creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address."> elements that have been visited by the user. Pseudo elements The:: pseudo represent entities that are not included in HTML.
      Example: p::first-line will match the first line of all element represents a paragraph.">

      elements.

      Specifications

      Specification Status Comment

      Selectors are one, if not the most important part of CSS. They form a cascade and define how styles should be applied to page elements.

      Until recently, the focus of CSS had never really been on selectors. Appeared from time to time minor updates within the selectors specification, but there were never any real groundbreaking improvements. Fortunately, in Lately More and more attention is being paid to selectors, so let's take a look at how to choose different types elements and elements in different states.

      CSS3 brought new selectors, opening up a whole new world opportunities and improvements to existing practices. Here we will discuss selectors, both old and new, and how to best use them.

      Typical selectors

      Before diving deep into some of the more complex selectors and those offered in CSS3, let's take a look at some of the most common selectors available today. These selectors include type, class, and identifier selectors.

      Selector type identifies an element based on its type, specifically how the element is declared in HTML. Selector class identifies an element based on the value of the class attribute, which can be reapplied to multiple elements as needed and helps share popular styles. And finally identifier defines an element based on the value of the id attribute that is unique and should only be used once on a page.

      H1 (...).tagline (...) #intro (...)

      Child selectors

      Child selectors provide a way to select elements that are nested within each other, making them children of their parent element. This selection can be made in two different ways, using a child selector or a direct child selector.

      Descendant selector

      The most common child selector is the descendant selector, which matches every element that follows a particular ancestor. The child does not have to come immediately after the ancestor in the document tree, like a parent-child relationship, but can be anywhere within the ancestor. Descendant selectors are created by space between the individual elements in the selector, creating a new level of hierarchy for each element in the list.

      The article h2 selector is a descendant selector and selects only elements

      , which are inside the element
      . Please note, no matter where the element lives

      while it is inside the element
      , it will always be selected. In addition, any element

      outside the element
      will not be selected.

      Below are the headings, from which lines 3 and 5 are selected.

      Article h2 (...)

      ...

      This title will be selected

      This title will be selected

      Direct child selector

      Sometimes child selectors go too far, selecting more than desired. Sometimes only the direct children of a parent element need to be selected, rather than every instance of an element nested deep within an ancestor. In this case, a direct child selector can be used by placing a greater than sign (>) between the parent and child element in the selector.

      For example, article > p is a direct child selector only when the elements

      Located directly inside the element

      . Any element<р>placed outside the element
      or nested inside another element other than
      , will not be selected.

      Below, the paragraph on line 3, is the only direct child of its parent

      , that's why it was chosen.

      Article > p (...)

      This paragraph will be selected

      Related selectors

      Knowing how to select child elements is largely useful and is quite common. However, sibling elements, that is, elements that share a common ancestor, may also need to be selected. Such a selection can be made using a common sibling selector and neighboring selectors.

      Generic sibling selector

      The general sibling selector allows you to select elements to be selected based on their siblings, i.e. those that have the same common parent. They are created by using the tilde character (~) between two elements within a selector. The first element specifies that the second element must be a sibling of it, and both must have the same parent.

      The h2~p selector is a general sibling selector, it searches for elements

      Which come after any elements

      in the same parent. To element

      Has been selected, it must come after any element

      .

      The paragraphs in lines 5 and 9 are selected because they come after a heading in the document tree and have the same parent as a related heading.

      H2 ~ p(...)

      ...

      This paragraph will be selected

      This paragraph will be selected

      Adjacent selectors

      Sometimes it may be desirable to have a little more control, including the ability to select a sibling that directly follows another sibling. An adjacent selector will only select sibling elements immediately following another sibling element. Instead of a tilde character, as is the case with a common sibling selector, a sibling selector uses a plus (+) symbol between two elements in the selector. Again, the first element specifies that the second element must immediately follow and be related to it, and both elements must have the same parent.

      Let's take a look at the adjacent selector h2 + p . Only elements will be selected

      Coming immediately after the elements

      . Both must also have the same parent element.

      The paragraph on line 5 is selected because it immediately follows its related heading and they share the same parent.

      H2 + p(...)

      ...

      This paragraph will be selected

      Example of adjacent selectors

      Input ( display: none; ) label, ul ( border: 1px solid #cecfd5; border-radius: 6px; ) label ( color: #0087cc; cursor: pointer; display: inline-block; font-size: 18px; padding: 5px 9px; transition: all .15s ease; ) label:hover ( color: #ff7b29; ) input:checked + label ( box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.15); color: #9799a7 ; ) nav ( max-height: 0; overflow: hidden; transition: all .15s ease; ) input:checked ~ nav ( max-height: 500px; ) ul ( list-style: none; margin: 8px 0 0 0; padding: 0; width: 100px; ) li ( border-bottom: 1px solid #cecfd5; ) li:last-child ( border-bottom: 0; ) a ( color: #0087cc; display: block; padding: 6px 12px; text-decoration: none; ) a:hover ( color: #ff7b29; )

      Attribute selectors

      Some of the generic selectors discussed earlier can also be defined as attribute selectors, in which an element is selected based on a class or id value. These selectors class attributes and id are widely used and quite powerful, but that's just the beginning. Other attribute selectors have emerged in recent years, notably making big leaps forward with CSS3. Elements can now be selected based on whether an attribute is present and what value it contains.

      Attribute presence selector

      The first attribute selector identifies an element based on whether the attribute is enabled or not, regardless of its actual value. To select an element based on whether an attribute is present or not, simply include the attribute name in square brackets() in the selector. Square brackets can come after any type or class selector, depending on the level of specificity desired.

      A (...)

      ...

      Attribute selector =

      To identify an element with a specific and precise value, the same selector can be used as before, but this time the desired value is included inside square brackets after the attribute name. Inside the square brackets there should be an attribute name following the equal sign (=), where the desired attribute value is written inside the quotes.

      A (...)

      ...

      Attribute selector *=

      When we are trying to find an element based on part of an attribute's value, but not an exact match, the asterisk (*) character within the selector's square brackets can be used. The asterisk must come immediately after the attribute name, immediately before the equals sign. This means that the value that follows only needs to appear or be contained in the attribute value.

      A (...)

      ...

      Attribute selector ^=

      In addition to selecting an element based on the attribute value containing specified text, you can also select an element based on where the attribute value begins. Using the circumflex character (^) in selector brackets between the attribute name and the equals sign means that the attribute value must begin with the specified text.

      A (...)

      ...

      Attribute selector $=

      The opposite of the previous selector is an attribute selector, where the value ends with some text. Instead of using the ^ character, a dollar sign ($) is used in the selector brackets between the attribute name and the equal sign. Using a dollar sign means that the attribute value must end with the specified text.

      A (...)

      ...

      Attribute selector ~=

      Sometimes attribute values ​​may be spaced apart from each other, in which only one of the words must be eligible to create a selection. In this case, using the tilde character (~) in the selector brackets between the attribute name and the equals sign means the attribute value is separated by spaces, of which one word exactly matches the specified value.

      A (...)

      ...

      Attribute selector |=

      When the attribute value is separated by hyphens rather than spaces, a vertical line character (|) can be used in the selector brackets between the attribute name and the equals sign. A vertical line indicates that the attribute value can be separated by a hyphen, but words must begin with the specified value.

      A (...)

      ...

      Example of attribute selectors

      Ul ( list-style: none; margin: 0; padding: 0; ) a ( background-position: 0 50%; background-repeat: no-repeat; color: #0087cc; padding-left: 22px; text-decoration: none; ) a:hover ( color: #ff7b29; ) a ( background-image: url("images/pdf.png"); ) a ( background-image: url("images/doc.png"); ) a ( background-image: url("images/image.png"); ) a ( background-image: url("images/audio.png"); ) a ( background-image: url("images/video.png" ); )

      Attribute selectors overview
      ExampleNameDescription
      aAttribute presence selectorSelects an element if the given attribute is present.
      aAttribute selector =Selects an element if the value of this attribute exactly matches the specified one.
      aAttribute selector *=Selects an element if the value of this attribute contains at least one instance of the specified text.
      aAttribute selector ^=Selects an element if the value of this attribute begins with the specified text.
      aAttribute selector $=Selects an element if the value of this attribute ends with the specified text.
      aAttribute selector ~=Selects an element if the value of the given attribute is separated by spaces and exactly matches a single specified word.
      aAttribute selector |=Selects an element if the value of the given attribute is separated by a hyphen and begins with the specified word.

      Pseudo-classes

      Pseudo-classes are similar to regular classes in HTML, however they are not directly specified in the markup; instead, they are populated dynamically as a result of user actions or document structure. The most common pseudo-class, and one you've probably seen before, is :hover. Note that this pseudo-class begins with a colon (:), like all other pseudo-classes.

      Link Pseudo-Classes

      Some basic pseudo-classes include two pseudo-classes that revolve around references. These are the :link and :visited pseudo-classes and they determine whether a link has or has not been visited. To style a link that has not yet been visited, the :link pseudo-class comes into play, and the :visited pseudo-class styles links that the user has already visited based on their browsing history.

      A:link (...) a:visited (...)

      User Action Pseudo-Classes

      Various pseudo-classes can be dynamically applied to an element based on user actions, including :hover, :active, and :focus. The :hover pseudo-class is applied to an element when the user moves the cursor over the element, most commonly used with links. The pseudo-class:active is applied to an element when the user activates the element, such as by clicking it. Finally, the pseudo-class:focus is applied to an element when the user has made the element the focus of the page, often by using the Tab key while moving from one element to another.

      A:hover (...) a:active (...) a:focus (...)

      Interface State Pseudo-Classes

      Like links, there are also some pseudo-classes associated with the state of UI elements, particularly within forms. These pseudo-classes include :enabled, :disabled, :checked, and :indeterminate.

      The :enabled pseudo-class selects fields that are enabled and available for use, and the :disabled pseudo-class selects fields that have a disabled attribute bound to them. Many browsers dim such disabled fields by default to inform users that the field is not available for interaction, but their styling can be customized as desired via the :disabled pseudo-class.

      Input:enabled (...) input:disabled (...)

      The last two interface state elements, the :checked and :indeterminate pseudo-classes, revolve around checkboxes and radio buttons. The :checked pseudo-class selects checkboxes or radio buttons that you might expect to be checked. When no checkbox or radio button is checked or selected, it lives in an indeterminate state, for which the :indeterminate pseudo-class can be used to target similar elements.

      Input:checked (...) input:indeterminate (...)

      Pseudo-classes of structure and position

      Several pseudo-classes refer to structure and position based on where elements are found in the document tree. These pseudo-classes come in different shapes and sizes, each providing its own unique functionality. Some pseudo-classes have been around longer than others, but CSS3 brought a whole new set of pseudo-classes to complement the existing ones.

      :first-child, :last-child and :only-child

      The first structural pseudo-classes you'll likely come across are :first-child , :last-child , and :only-child . The :first-child pseudo-class will select an element if it is the first child in the parent, while the :last-child pseudo-class will select the element if it is the last child in the parent. These pseudo-classes are ideal for selecting the first or last element in a list, etc. Additionally, :only-child will select an element if it is the only element in the parent. Alternatively, the :only-child pseudo-class can be written as :first-child:last-child , however :only-child has lower specificity.

      Here the selector li:first-child specifies the first list item, while li:last-child specifies the last list item, thus selecting rows 2 and 10. The div:only-child selector searches for

      , which is the only child of the parent element, with no other sibling elements. In this case, line 4 is selected because it is the only
      in this list item.

      Li:first-child (...) li:last-child (...) div:only-child (...)

      • This item will be selected
      • This div will be selected
      • ...
        ...
      • This item will be selected

      :first-of-type, :last-of-type and :only-of-type

      Finding the first, last and only child of a parent is very useful and often all that is required. However, sometimes you want to select only the first, last, or only child of a certain element type. For example, you want to select only the first or last paragraph within an article, or perhaps only an image within an article. Luckily, the :first-of-type , :last-of-type , and :only-of-type pseudo-classes help with this.

      The :first-of-type pseudo-class will select the first element of its type within the parent, while the :last-of-type pseudo-class will select the last element of that type within the parent. The :only-of-type pseudo-class will select an element if it is the only one of its type in the parent.

      In the example below, the pseudo-classes p:first-of-type and p:last-of-type will select, respectively, the first and last paragraphs in the article, regardless of whether they are actually the first or last children in the article. Lines 3 and 6 are selected by these selectors. The img:only-of-type selector specifies the image on line 5 as the only image appearing in the article.

      P:first-of-type (...) p:last-of-type (...) img:only-of-type (...)

      ...

      This paragraph will be selected

      This paragraph will be selected

      ...

      Finally, there are several structure and position pseudo-classes that select elements based on number or algebraic expression. These pseudo-classes include :nth-child(n) , :nth-last-child(n) , :nth-of-type(n) and :nth-last-of-type(n) . All of these unique pseudo-classes begin with nth and take a number or expression inside parentheses, which is denoted by the symbol n.

      The number or expression that is in parentheses specifies exactly which element or elements should be selected. Using a specific number will calculate the individual element from the beginning or end of the document tree and then select it. Using an expression will evaluate the set of elements from the beginning or end of the document tree and select a group or repetition of them.

      Using Numbers and Expressions in Pseudo-Classes

      As mentioned, using a specific number in a pseudo-class calculates from the beginning or end of the document tree and selects one matching element. For example, the selector li:nth-child(4) will select the fourth item in the list. The count starts from the first list item and increases by one for each list item until it finally finds the fourth item and selects it. When specifying a specific number, it must be positive.

      Expressions for pseudo-classes come in the format an, an+b, an-b, n+b, -n+b and -an+b. The same expression can be translated and read as (a×n)±b. The variable a denotes the factor by which the elements will be calculated, while the variable b denotes where the counting will begin or occur.

      For example, the selector li:nth-child(3n) will specify every third element of a list item. Using this expression corresponds to 3x0, 3x1, 3x2 and so on. As you can see, the results of this expression select the third, sixth, and every element that is a multiple of three.

      In addition, the odd and even keywords can be used as values. As you would expect, they will choose odd or even elements, respectively. If the keywords are not attractive, then the expression 2n+1 will select all odd elements, and the expression 2n will select all even elements.

      The selector li:nth-child(4n+7) will define every fourth item in the list, starting from the seventh item. Again, using this expression is equivalent to (4x0)+7, (4x1)+7, (4x2)+7, and so on. The results of this expression will select the seventh, eleventh, fifteenth, and every fourth element.

      When using n without a leading number, a is evaluated to 1. The li:nth-child(n+5) selector will select each list item starting with the fifth, leaving the first four list items unselected. In the expression this is parsed as (1×0)+5, (1×1)+5, (1×2)+5 and so on.

      Negative numbers can be used to create more complex things. For example, the selector li:nth-child(6n-4) will count every sixth list item, starting at -4, selecting the second, eighth, fourteenth list items, and so on. The same selector li:nth-child(6n-4) can also be written as li:nth-child(6n+2) , without using the negative b variable.

      A negative variable or negative argument n must be followed by a positive variable b. When argument n is preceded by a negative variable a, then variable b determines how high the count will be reached. For example, the selector li:nth-child(-3n+12) will select every third list item in the first twelve items. The selector li:nth-child(-n+9) will select the first nine items in the list, since the variable a without a declared number defaults to -1.

      :nth-child(n) and :nth-last-child(n)

      With a general understanding of how numbers and expressions work in pseudo-classes, let's take a look at useful pseudo-classes where these numbers and expressions can be used, the first of which are :nth-child(n) and :nth-last-child(n) . These pseudo-classes work similarly to :first-child and :last-child , in that they examine and count all the elements in the parent and select only a specific element. :nth-child(n) works from the beginning of the document tree, and :nth-last-child(n) works from the end of the document tree.

      Using the :nth-child(n) pseudo-class, let's take a look at the li:nth-child(3n) selector. It defines every third list item, so rows 4 and 7 will be selected.

      Li:nth-child(3n) (…)

      • This item will be selected
      • This item will be selected

      Using a different expression in the :nth-child(n) pseudo-class will produce a different selection. The selector li:nth-child(2n+3) , for example, will define every second item in the list, starting from the third. As a result, the items in lines 4 and 6 will be selected.

      Li:nth-child(2n+3) (...)

      • This item will be selected
      • This item will be selected

      Changing the expression again, this time with a negative value, will give a new choice. Here the selector li:nth-child(-n+4) specifies the top four items of the list, leaving the remaining items unselected, so rows 1 through 4 will be selected.

      Li:nth-child(-n+4) (...)

      • This item will be selected
      • This item will be selected
      • This item will be selected
      • This item will be selected

      Adding a negative number before n changes the selection again. Here the selector li:nth-child(-2n+5) defines every second list item from the first five items, so the items in lines 2, 4 and 6 will be selected.

      Li:nth-child(-2n+5) (...)

      • This item will be selected
      • This item will be selected
      • This item will be selected

      Changing the pseudo-class :nth-child(n) to :nth-last-child(n) switches the counting direction so that counting starts from the end of the document tree. The li:nth-last-child(3n+2) selector, for example, specifies every third list item, starting from the second to the last, moving towards the beginning of the list. Here the list items in lines 3 and 6 are selected.

      Li:nth-last-child(3n+2) (...)

      • This item will be selected
      • This item will be selected

      :nth-of-type(n) and :nth-last-of-type(n)

      The pseudo-classes :nth-of-type(n) and :nth-last-of-type(n) are very similar to :nth-child(n) and :nth-last-child(n) , but instead of counting each element Within the parent, the pseudo-classes :nth-of-type(n) and :nth-last-of-type(n) only count elements of their own type. For example, when counting paragraphs in an article, the :nth-of-type(n) and :nth-last-of-type(n) pseudo-classes will skip any headings

      or different elements that are not paragraphs, while :nth-child(n) and :nth-last-child(n) will count every element, regardless of its type, selecting only those that match the element in the specified selector. Additionally, all the same possible expressions used in :nth-child(n) and :nth-last-child(n) are also available in the :nth-of-type(n) and :nth-last-of-type pseudo-classes (n) .

      By using the :nth-of-type(n) pseudo-class in the p:nth-of-type(3n) selector, we can define every third paragraph in the parent, regardless of other related elements within the parent. Here the paragraphs on lines 5 and 9 are selected.

      P:nth-of-type(3n) (...)

      ...

      This paragraph will be selected

      ...

      This paragraph will be selected

      As with the :nth-child(n) and :nth-last-child(n) pseudo-classes, the main difference between :nth-of-type(n) and :nth-last-of-type(n) is that that :nth-of-type(n) counts elements from the beginning of the document tree, and :nth-last-of-type(n) counts elements from the end of the document tree.

      Using the pseudo-class :nth-last-of-type(n) we can write a selector p:nth-last-of-type(2n+1) that specifies every second paragraph from the end of the parent element, starting with the last paragraph. Here the paragraphs on lines 4, 7 and 9 are selected.

      P:nth-last-of-type(2n+1) (...)

      ...

      This paragraph will be selected

      ...

      This paragraph will be selected

      This paragraph will be selected

      Pseudo-class:target

      The :target pseudo-class is used to style elements when the value of the id attribute matches the URI fragment pointer. This portion of the URI is recognized by using the hash character (#) and what immediately follows it. The address http://example.com/index.html#hello includes a hello pointer. When it matches the value of the id attribute of an element on the page, for example,

      Pseudo-class:empty

      The :empty pseudo-class allows you to select elements that do not contain children or text. Comments, processing instructions, and empty text are not considered children and will not be treated as such.

      Using the div:empty pseudo-class will determine

      no children or text. Selected below
      in lines 2 and 3 because they are completely empty. Even though the second
      contains a comment, it is not considered a child, thus leaving
      empty. First
      contains text, the third one contains a single space, and the last one contains a child element , so they are all excluded and not selected.

      Div:empty (...)

      Hello

      Pseudo-class:not

      The :not(x) pseudo-class takes an argument and filters the selection that will be made. The p:not(.intro) selector uses the :not pseudo-class to define each paragraph without an intro class. The paragraph element is defined at the beginning of the selector, followed by the :not(x) pseudo-class. Inside the brackets is a negation selector, in this case the intro class.

      Below, both the div:not(.awesome) and :not(div) selectors use the :not(x) pseudo-class. The div:not(.awesome) selector defines any

      without class awesome , while the :not(div) selector specifies an element that is not
      . As a result, it is selected
      on line 1, as well as two sections on lines 3 and 4. The only item not selected is
      with the awesome class, since it goes beyond two pseudo-classes.

      Div:not(.awesome) (...) :not(div) (...)

      This div will be selected
      ...
      This section will be selected This section will be selected

      Example with pseudo-classes

      ...
      Number Player Position Height Weight
      8 Marco Belinelli G 6-5 195
      5 Carlos Boozer F 6-9 266

      Table ( border-collapse: separate; border-spacing: 0; width: 100%; ) th, td ( padding: 6px 15px; ) th ( background: #42444e; color: #fff; text-align: left; ) tr :first-child th:first-child ( border-top-left-radius: 6px; ) tr:first-child th:last-child ( border-top-right-radius: 6px; ) td ( border-right: 1px solid #c6c9cc; border-bottom: 1px solid #c6c9cc; ) td:first-child ( border-left: 1px solid #c6c9cc; ) tr:nth-child(even) td ( background: #eaeaed; ) tr:last- child td:first-child ( border-bottom-left-radius: 6px; ) tr:last-child td:last-child ( border-bottom-right-radius: 6px; )

      Pseudo-Classes Overview
      ExampleNameDescription
      a:linkLink pseudo-classSelects links that have not been viewed by the user.
      a:visitedLink pseudo-classSelects links that have been visited by the user.
      a:hoverAction pseudo-classSelects an element when the user hovers over it.
      a:activeAction pseudo-classSelects an element when the user activates it.
      a:focusAction pseudo-classSelects an element when the user has made it a point of attention.
      input:enabledState pseudo-classSelects an element in an accessible state.
      input:disabledState pseudo-classSelects an element in a disabled state, via the disabled attribute.
      input:checkedState pseudo-classSelects a checkbox or radio button that has been checked.
      input:indeterminateState pseudo-classSelects a checkbox or radio button that was not checked or unchecked, leaving it in an undefined state.
      li:first-childStructural pseudo-classSelects the first element in the parent.
      li:last-childStructural pseudo-classSelects the last element in the parent.
      div:only-childStructural pseudo-classSelects a single element in the parent.
      p:first-of-typeStructural pseudo-classSelects the first element of its type in the parent.
      p:last-of-typeStructural pseudo-classSelects the last element of its type in the parent.
      img:only-of-typeStructural pseudo-classSelects the only element of its type in the parent.
      li:nth-child(2n+3)Structural pseudo-classSelects an element that matches a given number or expression, counting all elements from the beginning of the document tree.
      li:nth-last-child(3n+2)Structural pseudo-classSelects an element that matches a given number or expression, counting all elements from the end of the document tree.
      p:nth-of-type(3n)Structural pseudo-classSelects an element that matches a given number or expression, counting only elements of that type from the beginning of the document tree.
      p:nth-last-of-type(2n+1)Structural pseudo-classSelects an element that matches a given number or expression, counting only elements of that type from the end of the document tree.
      section:targetPseudo-class:targetSelects an element whose id attribute value matches the URI fragment identifier.
      div:emptyPseudo-class:emptySelects an element that does not contain any children or text.
      div:not(.awesome)Pseudo-class:notSelects an element not represented by the declared argument.

      Pseudo-elements

      Pseudo-elements are dynamic elements that do not exist in the document tree and when used with selectors, these pseudo-elements produce unique parts of the page that can be styled. One important point to note is that only one pseudo element can be used in a selector at a time.

      Text pseudo-elements

      The first pseudo-elements implemented were the :first-letter and :first-line text pseudo-elements. The :first-letter pseudo-element specifies the first letter of text within an element, while :first-line specifies the first line of text within an element.

      In the demo below, the first letter of a paragraph with class alpha is set to a large font size and color, as is the first line of a paragraph with class bravo . This selection is made using the :first-letter and :first-line text pseudo-classes, respectively.

      Alpha:first-letter, .bravo:first-line ( color: #ff7b29; font-size: 18px; )

      Lorem ipsum dolor...

      Integer eget enim...

      Demonstration of text pseudo-elements

      Pseudo-elements generated content

      The :before and :after pseudo-elements create new inline pseudo-elements only within the selected element. Most often, these pseudo-elements are used in combination with the content property to add minor information to the page, however, this is not always the case. Additional use of these pseudo-elements can add user interface components to a page without having to clutter the document with non-semantic elements.

      The :before pseudo-element creates a pseudo-element before or in front of the selected element, while :after creates a pseudo-element after or behind the selected element. These pseudo-elements appear nested within the selected element rather than outside it. Below, the :after pseudo-element is used to display the href attribute value of links in parentheses after the link itself. This information is useful, but ultimately, not every browser supports these pseudo-elements.

      A:after ( color: #9799a7; content: " (" attr(href) ")"; font-size: 11px; )

      Search on the Internet Learn how to create a website

      Demonstration of pseudo-elements generated by content

      Pseudo-element::selection

      The ::selection pseudo-element defines the user-selected portion of the document. The selection can then be styled, but only using the color , background , background-color and text-shadow properties. It's worth noting that the background-image property is ignored. However, the shorthand background property can be used to add color, but any images will be ignored.

      Colon (:) and double colon (::)

      The ::selection pseudo-element was added to CSS3 in an attempt to separate pseudo-classes from pseudo-elements by using the double colon that was added to pseudo-elements. Fortunately, most browsers will support both single and double colon values ​​for pseudo-elements, but the ::selection pseudo-element must always begin with a double colon.

      When you select any text in the demo below, the background turns orange thanks to the ::selection pseudo-element. Also take a look at ::-moz-selection. The Mozilla prefix has been added to provide better support for all browsers.

      ::-moz-selection ( background: #ff7b29; ) ::selection ( background: #ff7b29; )

      Pseudo-elements demonstration

      Continue reading

      Arrow ( background: #2db34a; color: #fff; display: inline-block; height: 30px; line-height: 30px; padding: 0 12px; position: relative; text-decoration: none; ) .arrow:before, . arrow:after ( content: ""; height: 0; position: absolute; width: 0; ) .arrow:before ( border-bottom: 15px solid #2db34a; border-left: 15px solid transparent; border-top: 15px solid #2db34a; left: -15px; ) .arrow:after ( border-bottom: 15px solid transparent; border-left: 15px solid #2db34a; border-top: 15px solid transparent; right: -15px; ) .arrow:hover ( background: #ff7b29; ) .arrow:hover:before ( border-bottom: 15px solid #ff7b29; border-top: 15px solid #ff7b29; ) .arrow:hover:after ( border-left: 15px solid #ff7b29; )

      Browser selector support

      While these selectors offer different capabilities and the ability to do some truly amazing things with using CSS, they sometimes suffer from poor browser support. Before doing anything too critical, check the selectors you want to use in the most popular browsers and then decide whether they suit you or not.

      CSS3.info offers a CSS3 Selectors Test tool that will inform you which selectors are supported by the browser. It's also a good idea to check your browser's support directly.

      On Smashing Magazine

    • Understanding:nth-child Pseudo-class Expressions on SitePoint
    • Taming Advanced CSS Selectors on Smashing Magazine


    • tell friends