Selector determines which element to apply a particular CSS rule to.
Basic selectors
Element Selectors This basic selector selects the element to which the rule will be applied. Syntax:element Example: the input selector will select all elements used to create interactive controls in web forms. "> ... Selectors by Class This basic selector selects elements based on the value of their class attribute. Syntax: .class name Example: the .index selector will select all elements with the appropriate class (which was defined in the attribute class = "index" or similar). ID Selectors This basic selector selects elements based on the value of their id attribute. Remember that the identifier must be unique, that is, it must be used for only one element in the HTML document. Syntax:#IDName Example: the #toc selector will select the element with the id toc (which was defined in the id = "toc" or similar attribute). Universal Selector This basic selector selects all items. It also exists in local and global namespaces. Syntax:* ns | * * | * Example: selector * will select all elements. Attribute Selectors This basic selector selects elements based on one of their attributes and / or its value. Syntax: Example: the selector will select all elements with the autoplay attribute (regardless of its value).
Combinators
The + combinator matches an element that is immediately after the specified element if they have a common parent. Syntax: A + B Example: the ul + li selector will select any element that is immediately after the element
... Related Selectors The "~" combinator selects items after the specified item if they have a common parent. Syntax: A ~ B Example: p ~ span will select all elements that follows the element defines a paragraph of text. ">
inside one parent. Child Selectors The> combinator selects elements that are directly children of the specified element. Syntax: A> B Example: the ul> li selector will select all elements that are inside the element
element. Nested Selectors The "" combinator selects elements that are within the specified element (regardless of the nesting level). Syntax: A B Example: the div span selector will select all elements that are inside the element) is the base container for the main flow elements (flow content). It does not affect content or format until styled using CSS. While "> does not inherently represent anything. In the meantime, it is used to group content so that it can be easily styled using">
.
Pseudo-elements
Pseudo-elements are abstract, unlike HTML elements responsible for the presentation. For example, in HTML there is no individual elements to indicate the first letter or first line of text, or a bullet for an unordered list. Pseudo-elements denote such objects and provide the ability to style them with CSS.
Pseudo-classes
Pseudo-classes allow you to select items based on information that is not in the item tree, such as state or other data that is difficult to extract in any other way. For example, they can select a link that has or has not been previously visited.
Specifications
Specification
Status
Selector in CSS - this is a pointer the element or group of elements to which the style rules will be applied. There are the following types of selectors:
1. Tag selectors: h1
2. Selector by id: #main
3. Class selectors: .hidden
4. Selector for several classes
Written together without spaces. Selectors that satisfy several conditions at once (logical "AND"). Styles will be applied to all elements that have both .hidden and .closed classes at the same time.
Separated by a space. Such selectors are used to apply styles to an element only if it nested to the desired item.
P strong ul .selected .header .menu a
6. Adjacent selectors
Selects the subsequent item. They are written using the + sign. It reads like: apply properties to selector2 which should be right after selector1.
Styles are applied to an element matching selector2 only if it is preceded by an element matching selector1.
... .green + .selected ()
In the example ,.green + .selected will apply styles to the second element, since before it there is an element with the class.green. The.green + li selector will style the second element too, and the .selected + .green selector will not work.
7. Related selectors
Highlights subsequent elements... Similar to the previous one, but with the difference that selects all of the following items, not just the first element.
item
Selected too
Not selected ... ul ~ p ()
V this example all p elements following the ul will be selected. Whereas when using the ul + p selector, only the first element will be selected.
8. Child selectors
They are written using the> sign and apply only to elements of the first nesting level. Elements nested within other elements are not affected.
Ul> li ( }
In the case of contextual selectors, they affect all descendants (for example, if you set ul li), which is not always convenient. Child selectors allow you to style only the first level of nesting.
ul> li means the same as ul li, but only the first nesting level li that are directly nested in ul are selected. On li elements nested in other child li elements, the rules will no longer apply.
9. Attribute selectors
Most often used when working with forms. Attribute selectors are written using square brackets on the [attribute] element.
Examples of attribute selectors:
Input input div a a a a
In the example above, ~ allows you to highlight a specific attribute from a comma-separated list of attributes, for example from:
bar">
10. Global selector
Selector * will select all elements. It can also be used to highlight children:
For the first time, we met CSS selectors See Lesson 9 of the CSS Tutorial for more information. In this article, we will explore selectors in more detail, as well as look at other types of CSS selectors.
Selector(from English selector) - sorting, selection. Selectors, in CSS, mean a way to select elements (tags) of a page.
As we know from, the CSS code scheme looks like this:
There are three main types of selectors and their different relationships. In addition, there is a universal selector, attribute selectors, attribute and value selectors, and their selection using regular expressions.
Usually, when creating a site, only basic selectors are used.
Basic types of CSS selectors
1. Tag selector- selection of a page element by the name of its tag nameTag ()
2. Class selector- selection of a page element by its class name .ClassName ()
3. Id selectors- selection of a page element by the name of its unique identifier #NameUniqueIdentifier ()
Relationships between CSS selectors
The relationship between selectors is when a character is placed between them in the CSS code: a space, a comma, an angle bracket, etc. Thus, you can select any element on the page more precisely.
1. Contextual selectors- selection of descendant elements selector selector () (space between selectors).
2. Child selectors- selection of child elements selector> selector () (between selectors put a greater than sign).
3. Adjacent selectors- selection of adjacent (sibling, sibling) elements selector + selector () (a plus sign is placed between the selectors).
If something is not clear, do not worry, we will consider each selector and their relationship separately, in articles dedicated only to them, but I will add these articles 🙂
Attribute and value selectors
Attribute and value selectors- select elements by their attribute or attribute and value.
1. Attribute selector- selection of an element by attribute name [attribute] ()
2. Attribute and value selector- selection of an element by its attribute name and value [attribute = "value"] ()
Universal selector
In CSS code, universal selector write as an asterisk * The universal selector is required to to set CSS properties for all page elements at once. Usually it is used to reset the padding of elements, for example:
* (margin: 0; padding: 0;)
All page elements have margins equal to 0.
Grouping selectors
Grouping selectors- selection of several selectors and assignment of certain CSS-properties to them, scheme:
Selector, selector ()
Use a comma between selectors.
CSS contains style rules that are interpreted by the browser and then applied to the appropriate elements in your document. The style rule has three parts:
Selector is the HTML tag to which the styling will be applied. It can be any tag, for example
or
etc.
Property is an attribute type of an HTML tag. Simply put, all attributes in HTML are converted to CSS properties. They can be colors, borders, padding, etc.
Meaning- set to the property. For example, a color property could be green, # 008000, etc.
The syntax for CSS selectors is as follows:
Selector (property: value)
Example. You can set the border of the table as follows:
Table (border: 2px solid # FF8C00;)
Here the syntax for the selector is: table is the selector and border is a property, and 2px solid # FF8C00 is the value of that property.
You can set selectors different ways as it is convenient for you. Below are the types of selectors.>
Standard selectors
This is the same selector you saw above. Again, another example to give color to all first level headings:
H1 (color: # 8B4513;)
Universal selectors
Rather than selecting elements of a specific type, the universal selector quite simply matches the name of any element type:
* (color: # 808080;)
This rule renders the content of each element in gray in our document.
Descendant selectors or nested selectors
Suppose you want to apply a style rule to a specific element only when it is inside a specific element, then nested selectors or descendant selectors will help you with this. As shown in the following example, the style rule will be applied to the element only when it is inside a tag
.
Ul em (color: # CD5C5C;)
Class selectors
You can set style rules for elements based on the class attribute. All elements that have this class will be formatted according to a certain rule.
Blue (color: # 0000FF;)
class = "blue"... You can make the class selector a little more specific. For example:
H1.blue (color: # 0000FF;)
with attribute class = "blue".
You can apply multiple class selectors to one element. Consider next example:
This paragraph will be formatted with classes center and bold.
ID selectors
You can set style rules for elements based on the id attribute. All items with this identifier will be formatted according to a specific rule.
#blue (color: # 0000FF;)
This rule renders the content in our document in blue for each element with the attribute id = "blue"... You can make the id selector a little more specific. For example:
H1 # blue (color: # 0000FF;)
This rule renders content in blue for elements only
with attribute id = "blue".
The true power of id selectors is when they are used as the basis for descendant selectors, for example:
#blue h2 (color: # 0000FF;)
In this example, all second-level headings will appear in blue when they are in tags with the attribute id = "blue".
Child selectors
You already know the descendant selectors. There is another type of selector that is very similar to descendant selectors, but has different functionality, which is a child selector. Consider the following example:
Body> p (color: # 0000FF;)
This rule will render all paragraphs in blue if they are straight child element
... Other paragraphs placed inside other elements like
or
Adjacent selectors
HTML elements that follow each other are called siblings. Consider the following example:
Strong + em (color: # 0000FF;)
This rule will display the content of the tag in blue if it comes after the item ... Other tags not after the tag will have no effect on this rule.
Attribute selectors
You can also apply styles to HTML elements with specific attributes. Below style rule will match all input elements having type attribute with text value:
Input (color: # 0000FF;)
The advantage of using attribute selectors is that the element does not change, and the color is applied only to the desired text boxes.
For an attribute selector, the following rules apply:
p - Selects all paragraph elements with the lang attribute.
p - Selects all paragraph elements where the lang attribute has the exact value "ru".
p - Selects all elements in a paragraph where the lang attribute contains the word "ru".
p - Selects all elements in a paragraph where the lang attribute contains values that are exact "ru" or start with "ru".
Several style rules
You may need to define multiple style rules for the same element. You can set these rules to combine multiple properties and corresponding values into a single block, as shown in the following example:
Separate all pairs of properties and values with a semicolon (;). You can store them on one line or multiple lines. Save them on separate lines for better readability.
Don't worry about the properties mentioned in the above block. These properties will be explained in the next lessons.
Grouping selectors in CSS
You can style many selectors if you like. Just separate the selectors with a comma as shown in the following example:
This style rule will be applied to the h1, h2 and h3 elements. The order of the list is irrelevant when grouping selectors. All elements in the selector will have corresponding declarations applied to them.
You can group different selector ids together as shown below:
Today we will look at the concept of CSS selectors and how we can use them to shorten our HTML markup, making it cleaner.
The CSS selector is the element we are going to apply CSS properties to. The word "selector" speaks for itself; it denotes a choice.
P (color: red) div span (background: green) ul li (list-style: none)
Class and id selectors
In the example above, we have 3 selectors - these are p, div span, ul li. That is, our entire style file consists of selectors and their properties. It is most convenient and clear, especially for beginners, to take the name of the class (class) of the tag or the unique identifier (id) of the tag for the selector. To assign a class or ID to a tag, we must list it among the attributes of that tag. A particular tag can have a maximum of 1 identifier and infinite number classes. Example:
text in the first diva
text in the second diva
text in the third diva
What you should pay attention to:
Classes and identifiers can be assigned to any (all) tags.
Each id is unique and cannot be repeated within the same page, unlike classes!
The same class can be assigned to any tags and can be repeated any number of times on the page.
If we want to assign several classes to a specific tag, we simply specify them separated by a space.
The names of the classes and identifiers can be the same, and apart from the name, there will be nothing in common between them.
How do I refer to a class or id in a stylesheet (CSS) file?
Let's see an example:
#first (color: red;) / * access id named first * /.second (color: blue;) / * refer to the class named second * /#first .second (color: orange;) / * refer to the class named second ONLY if it is INSIDE the tag with the identifier first * /.first .third (color: gray;) / * refer to a class named third ONLY if it is INSIDE a tag with class first * /
In our case, the last two instructions will not work, since we do not have classes nested inside tags with given attributes... As you may have noticed, to indicate that we are referring to id, we need to put a pound sign (#) in front of its name without spaces, if we are referring to a class, then we must put a period (.) In front of the class name.
The use of classes and identifiers is very convenient, but it increases our HTML markup, ideally (which never does) we shouldn't use them at all, instead we will use combinations and groupings of selectors, the rest of the article will be about them, but! But this does not mean at all that you should completely abandon the use of classes and identifiers, you just have to keep in mind that very often, instead of creating a new class or id, you can get by with the techniques described below, and they can also be quite convenient.
What is the difference between class and id?
In addition to the above differences, it is also worth noting that properties set by id have a higher priority than properties set to a class. That is, if we write:
text in diva
Then the color of the text will turn red, despite the fact that the class is lower in the code and if they had equal priority, the text would turn blue.
By syntax: in cases with a class, we can choose which tag should have this class, for this, after the tag name WITHOUT a space, we must refer to the class. Example:
Myclass (properties) / * will apply to all tags that contain myclass * / div.myclass (properties) / * will only apply to div tags that contain the class myclass * /
For id, this will also work, but such a record makes no sense, since id cannot be repeated on the page, which means that it is enough to simply declare the id, without the tag to which it belongs:
text
It seems that there is only one unspecified difference left, and it concerns a topic that in the near future I did not plan to touch on on this blog - Javascript. But still I must inform you about it: if you want to refer to an element with using Javascript, then for this purpose it will be very convenient to have an id for this element. To refer to an element by its class in Javascript there is no such built-in feature, you have to use secondary functions+ it's not always cross-browser.
Bottom line: we use id and class, but in moderation, while always asking ourselves, is it possible to do without them here and how expedient it is.
Sibling selector
Div p (color: green;) / * Descendant selector * / p (color: red;) / * tag selector * /
But as I wrote in the previous article, in the first case, CSS properties will be applied to all p tags nested to ANY depth of the div tag. But what if we want to apply properties only to direct descendants, that is, to the first nesting level:
Third level
Direct heir (first level)
Second level
Direct heir (first level)
In this case, we must use the so-called related selector, an angle bracket is used to denote it, you can use spaces, you can leave them alone, I would not advise:
Div> p (color: blue;) / * only the first level of nesting * / div p (color: blue;) / * absolutely all paragraphs inside the div * /
Universal selector
We figured out this, we already have 3 types of selectors in our arsenal, now I want to tell you about a very unusual selector that stands out from all the others - this is the so-called universal selector, which is indicated by an asterisk (*):
By the way, when working with selectors, as with any work related to layout, it is very convenient to view page elements. If you are not yet aware of such things as Opera Dragonfly, Firebug and web inspectors in general, then you, without exaggeration, urgently need to read the article at the link above! And who has already used such things, please follow me further.
Pseudo-classes
Unlike classes, pseudo-classes do not need to be specified in the HTML markup, they are calculated by the browser themselves. We have 4 static pseudo-classes and 3 dynamic pseudo-classes, excluding CSS 3, more on that towards the end. Static include (: first-child,: link,: visited,: lang ()):
Direct heir (first level)
Third level
Direct heir (first level)
Second level
Direct heir (first level)
Result:
Naturally, you can combine the selectors as you like, for example:
Div> span p: first-child (color: green;) / * fires if p is the first child of its parent and is inside a span tag that is a direct child of a div * /
The name of the above pseudo-class speaks for itself first-child - the first child.
The next two static pseudo-classes only apply to the hyperlink tag (: link,: visited), they apply CSS properties depending on whether they were visited. given linkspecific user or not:
A: link (color: blue;) / * unvisited links have blue color, and by default they are underlined * / a: visited (color: green; text-decoration: none;) / * the text of visited links will be red, remove the underline * /
The: lang () pseudo-class is used to specify different styling depending on the language. The brackets indicate the language to which you want to apply the design. This can be used, for example, to assign different styles quotes in quotes:
Q: lang (de) (quotes: "\ 201E" "\ 201C";) / * quotes for German * / q: lang (en) (quotes: "\ 201C" "\ 201D";) / * quotes for English * / q: lang (ru) (quotes: "\ 00AB" "\ 00BB";) / * quotes for Russian * /
This is perhaps the only one of all the possible kinds of selectors that I have never used.
Dynamic pseudo-classes
Dynamic pseudo-classes are: active,: hover,: focus. Dynamic pseudo-classes are triggered by a specific action on the page, they work for all tags, and not just for links as many people think and even claim in their blogs! Let's consider their application:
P: active (background: red;) / * style that will be applied to the tag on clicking on it (mouse click) * / input: focus (width: 400px;) / * style that will be applied to the element on which this moment focus (works, for example, for text input fields: textarea, input). V in this case on focus, the input width will become 400 pixels, it is convenient to use for beautiful effect lengthening the field by clicking. * / div: hover (background: green;) / * triggers on hovering over an element, mainly used to create a nice hover effect on links. * /
Apply these styles to our example above, and you will see everything for yourself.
Adjacent selectors
Adjacent selectors are the nearest neighbor in the code below, not a child! A very handy selector:
the text in the paragraph of the first div
text in paragraph OUTSIDE div
the text in the paragraph of the second div
text in span
again the paragraph outside the div
Result:
Generalized Adjacent Selectors
Generic Adjacent Selectors act exactly like regular Adjacent Selectors, except that the properties apply not only to the first neighbor below, but to all specified neighbors below:
text in diva
paragraph
paragraph
paragraph
text in span
paragraph
paragraph
paragraph in diva
paragraph in diva
text in span
paragraph
Result:
Attribute selectors
Attribute selectors allow us to refer to tags that have an attribute we need, or even a specific value:
P (properties) / * apply to all p tags that have an align attribute * / p (properties) / * where the value of the align attribute is center * / p (properties) / * where the value of the align attribute starts with center * / p (properties) / * where the value of the align attribute contains center * / p (properties) / * where site can appear among other words separated by spaces () * / p (properties) / * where the value of the class attribute consists only of or begins with the word site, followed by a hyphen and the rest of the value (or) * / p (properties) / * where the value of the align attribute ends with center * /
CSS 3 pseudo-classes
You have already familiarized yourself with all the main selectors and in the first couples this should be enough with a slide. However, a lot of new pseudo-classes appeared in CSS 3, now we can take not only the first child, but also any other one in a row, we can go from the opposite, take not the first, but the last child, and so on and so forth. All this is very convenient and practical, unless you may have problems with older versions of IE. Let's gather all our strength into a fist and go over all the remaining selectors, so that later you can have them in mind when making up your own layout.
: last-child - similar to: first-child, only takes not the first, but the last child.
: only-child - will be triggered if the element (tag) is the only child.
: only-of-type - will be triggered if the element (tag) is the only child of its type.
: nth-child () - refers to children by their serial numbers, you can refer to all odd or even (even or odd) numbers. For example:
paragraph
paragraph
paragraph
text in span
paragraph
paragraph
paragraph
paragraph
paragraph
paragraph
Result:
: nth-last-child - works the same as the previous one, but the report starts from the end.
: first-of-type - the first child of its type within the direct parent.
: last-of-type - the last child of its type within the direct parent.
: empty - will work for those tags with no characters inside (no text).
: not () - Throws an exception for the given items. Example:
a paragraph with a roll class
paragraph
paragraph
a paragraph with a roll class
Result:
Controlling fields, forms, radio buttons and checkboxes in CSS
: enabled - applies to available interface elements like forms, buttons, radio buttons, etc. By default, all interface elements are accessible.
: disabled - applies to disabled interface elements like buttons, forms, and so on. Interface elements are disabled if you add the disabled attribute to them in HTML or disabled = ”disabled” in XHTML.
: checked - Applies to interface elements such as radio and checkbox when they are in the on position.
Pseudo-elements
Pseudo-elements, like pseudo-classes, are calculated automatically by the browser, we don't need to worry about that. In order not to confuse pseudo-elements with pseudo-classes in CSS specifications 3, it was decided to use a double colon instead of a single colon, as was the case in CSS 2. Therefore, on the Internet you can find pseudo-elements with both a single colon and a double - both are correct. However, for better compatibility with IE, it is recommended to use a single colon.
: first-line is the first line inside a block or table element.
: first-letter is the first letter inside a block element.
Bottom line: now you know and can use the full power of cascading style sheets, but this does not mean that you need to immediately rush to typeset site layouts using as many selectors, pseudo-classes and pseudo-elements studied today as possible. I have listed all the possible tools, and you should choose only the most necessary for yourself.
Benefits of HTML Optimization with CSS
Part of the point above is to move away from ubiquitous use. class attributes and id in HTML, leaving it all on the shoulders of mighty stylesheets.
External style files, just like external Javascript files are perfectly cached, which means that after visiting any page of your site for the first time, the user's browser remembers these files and does not download them anymore, unlike the site page itself, that is, your HTML markup, pictures and text, which the browser loads again and again. The same goes for search engines, they don't care about yours at all. external files, but they do care about the scope and content of your HTML markup. Search Engines you have to scan the entire structure of the page and it is in your best interest to help them with this, focus their efforts on the content, and not on a cumbersome wall of markup consisting of a bunch of classes and identifiers or even worse - Javascript event handlers and CSS styles right in the tag attributes (and this still happens).
You can argue with me, they say, we can force the client browser to download itself in local environment all include files, pictures, cache the entire page, and so on and so forth. Against such a background, such a trifle is completely lost, but one way or another, by reducing the HTML markup as much as possible, you only win, while losing nothing, except for a possible habit.
To summarize: thanks to HTML optimization and shortening, we have a very small gain in site load speed and in SEO ( search engine optimization) as well as cleaner code.