Selectors in CSS. Class and id selectors


CSS contains style rules that are interpreted by the browser and then applied to appropriate elements in your document. A style rule consists of three parts:

  • Selector is the HTML tag to which the style will be applied. This 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. These can be colors, borders, padding, etc.
  • Meaning- is set to the property. For example, the color property could be green, #008000, etc.
  • The syntax for selectors in CSS is as follows:

    Selector ( property: value )

    Example. You can set the table border like this:

    Table ( border: 2px solid #FF8C00; )

    Here the selector syntax is: table is the selector and border is the property and 2px solid #FF8C00 is the value of that property.

    You can specify selectors different ways, as it will be convenient for you. Below are the types of selectors.>

    Standard selectors

    This is the same selector that you saw above. Again, another example to give color to all first level headings:

    H1 ( color: #8B4513; )

    Universal selectors

    Instead of selecting elements of a specific type, a universal selector quite simply matches the name of any element type:

    * ( color: #808080; )

    This rule displays the contents of each element in our document in gray.

    Descendant selectors or nested selectors

    Suppose you want to apply a style rule to a certain element only when it is inside a certain 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. Let's 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 elements that have this ID will be formatted according to a certain rule.

      #blue ( color: #0000FF; )

      This rule displays 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 displays content in blue only for elements

      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 descendant selectors. There is another type of selector that is very similar to child selectors but has different functionality, the child selector. Consider the following example:

      Body > p ( color: #0000FF; )

      This rule will display all paragraphs in blue if they are straight child element . Other paragraphs placed inside other type elements

      or

    Adjacent selectors

    HTML elements that follow each other are called adjacent elements. Consider the following example:

    Strong + em ( color: #0000FF; )

    This rule will display the contents of the tag in blue if it comes after the element . Other tags , not coming after the tag , will have no effect of this rule.

    Attribute selectors

    You can also apply styles to HTML elements with certain attributes. The style rule below 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 fields.

    The following rules apply to the attribute selector:

    • 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 paragraph elements where the lang attribute contains the word "ru".
    • p - selects all paragraph elements where the lang attribute contains values ​​that are the exact "ru" or begin with "ru".

    A few style rules

    You may need to define multiple style rules for a single element. You can define these rules to combine multiple properties and their corresponding values ​​into a single block, as shown in the following example:

    H1 ( color: #00CED1; letter-spacing: .2em; text-transform: lowercase; margin-bottom: 2em; font-weight: 700; )

    All property and value pairs are separated by a semicolon (;). You can store them on one line or multiple lines. For better readability, keep them on separate lines.

    Don't worry about the properties mentioned in the above block. These properties will be explained in the following lessons.

    Grouping selectors in CSS

    You can style many selectors if you want. Simply separate the selectors with a comma, as shown in the following example:

    H1, h2, h3 ( color: #00CED1; letter-spacing: .2em; text-transform: lowercase; margin-bottom: 2em; font-weight: 700; )

    This style rule will be applied to the h1, h2 and h3 elements. The order of the list does not matter when grouping selectors. All elements in the selector will have corresponding declarations applied to them.

    You can group different selector id's together like below:

    #header, #content, #footer ( position: absolute; width: 300px; left: 250px; )

    Greetings, dear readers. In previous articles, we studied mainly CSS style attributes. There are a lot of them. Some set the font parameters, others the background parameters, and still others the parameters for indents and frames.

    In this article we will talk about style selectors. In one of the articles we already touched upon. Today we’ll look at several more types of selectors that do not explicitly bind a style rule to a web page element. These are so-called special selectors. There are several types of them.

    Combinators in CSS (Adjacent, Child and Context Selectors)

    Combinators are a type of CSS selectors that bind a style rule to a web page element based on its location relative to other elements.

    First combinator symbol plus(+) or adjacent selector. Plus is set between two selectors:

    <селектор 1> + <селектор 2> { <стиль> }

    The style in this case is applied to selector 2, but only if it is adjacent to selector 1 and comes right after it. Let's look at an example:

    strong + i (

    }
    ...

    This is normal text. This is bold text, plain text, red text


    This is normal text. This is bold text, plain text, and this is normal text.

    Result:

    The style described in the example will be applied only to the first text enclosed in the tag , because it comes immediately after the tag .

    Combinator tilde(~) also applies to adjacent selectors, but this time there may be other elements between them. In this case, both selectors must be nested in the same parent tag:

    <селектор 1> ~ <селектор 2> { <стиль> }

    The style will be applied to selector 2 which should follow selector 1. Consider an example:

    strong~i(
    color:red; /* Red text color */
    }
    ...

    This is normal text. This is bold text, plain text, red text the adjacent selector rule applied to it.


    This is normal text. This is bold text, plain text, and this is red text.

    Result:

    As you can see, this time the style rule worked for both texts enclosed in the tag , despite the fact that in the second case between the tag And worth the tag .

    Combinator > refers to child selectors . Allows you to bind CSS style to a web page element that is directly nested within another element:

    <селектор 1> > <селектор 2> { <стиль> }

    Style will be tied to selector 2, which is directly nested in selector 1.

    div > strong (

    }
    ...

    This is normal text. This is bold italic text.

    This is normal text. And this is regular bold text.


    And the result:

    As you can see in the figure, the style rule only affected the first tag , which is directly nested within the tag

    . And the immediate parent of the second tag is the tag

    , so the rule does not apply to him.

    Next we'll look at context selector<пробел> . It allows you to bind a CSS style to an element nested within another element, and there can be any level of nesting:

    <селектор 1> <селектор 2> { <стиль> }

    The style will be applied to selector 2, if it is somehow nested in selector 1.

    Let's look at the previous example, only when describing a CSS rule we use the context selector:

    div strong(
    font-style: italic /* Italic */
    }
    ...

    This is normal text. This is bold italic text.

    This is normal text. And this is also italic bold text.



    Plain text and just bold text

    Result:

    As you can see, this time the rule affected both tags , even one that is nested in a container

    and into a paragraph

    . To tag , which is simply nested within a paragraph

    css rule doesn't work at all.

    Selectors by tag attributes

    Attribute selectors are special selectors that bind a style to an element based on whether it contains a certain attribute or has a certain value. There are several options for using such selectors.

    1. Simple attribute selector

    Looks like:

    <селектор>[<имя атрибута тега>] { <стиль> }

    And binds the style to those elements within which the specified attribute is added. For example:

    strong(
    color:red;
    }
    ...

    Automobile this is a mechanical motor trackless vehicle">road vehicle with at least 4 wheels.

    Result:

    In the picture you can see that the css rule (red text color) is applied to the element strong, to which the attribute is added title.

    2. Attribute selector with value

    The syntax for this selector is as follows:

    <селектор>[<имя атрибута тега>=<значение>] { <стиль> }

    Binds style to elements whose tags have an attribute with the specified name And meaning. Example:

    a(
    color:red;
    font-size:150%;
    }
    ...
    .ru" target="_blank">Link in new window

    Result:

    As you can see, both elements of the hyperlink type have the attribute target, but the css rule that enlarges the link text by one and a half times and changes its color to red is applied to the tag whose attribute target has the meaning "_blank".

    3. One of several attribute values

    Some attribute values ​​may be separated by spaces, such as class names. To set a style rule when the required value is present in the list of attribute values, use the following selector:

    [<имя атрибута тега>~=<значение>] { <стиль> }
    <основной селектор>[<имя атрибута тега>~=<значение>] { <стиль> }

    The style is applied if the attribute has the required value or is part of a space-separated list of values. For example:

    {
    color:red;
    font-size:150%;
    }
    ...

    Our phone: 777-77-77


    Our address: Moscow st. Sovetskaya 5

    You will get the following result:

    The rule applies to an element whose attribute values ​​include: class there is a meaning tel.

    4. Hyphen in attribute value

    A hyphen is allowed in identifier and class values. To bind a style to elements whose attribute values ​​may contain a hyphen, you can use the following construction:

    [attribute|="value"] ( style )
    Selector[attribute|="value"] ( style )

    The style is applied to those elements whose attribute value begins with the specified value followed by a hyphen. For example:

    {
    color:red;
    font-size:150%;
    }
    ...



    • Point 2



    Result:

    In the example, the style rule applies only to those list elements whose class name begins with value "menu- „.

    5. The attribute value starts with specific text

    This selector sets the style for an element if the tag attribute value starts with a specific value. There may be two options:

    [<имя атрибута тега>^=<подстрока>] { <стиль> }
    <основной селектор>[<имя атрибута тега>^=<подстрока>] { <стиль> }

    In the first case style applies to all elements whose tags have an attribute with the specified name and a value starting with the specified substrings. In the second case, the same thing, only to certain elements specified in main selector. Example:

    a(
    color:green;
    font-weight:bold;
    }
    ...

    Result:

    The example shows how to display external links and internal links. External links always start with the line “http://”. Therefore, in the selector we indicate that the style will be applied only to links that have the attribute href starts with meaning http://.

    6. The attribute value ends with certain text

    Binds a style to elements whose attribute value ends with the specified text. Has the following syntax:

    [<имя атрибута тега>$=<подстрока>] { <стиль> }
    <основной селектор>[<имя атрибута тега>$=<подстрока>] { <стиль> }

    In the first case style applies to all elements that have attribute with the specified name and has a meaning ending with the specified substring. In the second case, the same thing, only to the indicated selectors. In this way, for example, you can display various formats graphic images. For example:

    IMG (
    border: 5px solid red;
    }
    ...

    GIF image



    Picture format png


    Result:

    In the example, all images with a gif extension will be displayed with a red border five pixels thick.

    7. The attribute value contains the specified string

    This selector binds a style to tags whose attribute value contains specific text. Syntax:

    [<имя атрибута тега>*=<подстрока>] { <стиль> }
    <основной селектор>[<имя атрибута тега>*=<подстрока>] { <стиль> }

    Style binds to elements that have attribute With specified name and its value contains the specified substring. For example:

    IMG (
    border: 5px solid red;
    }
    ...

    Picture from the gallery folder



    Picture from another folder


    Result:

    In the example, the style is applied to pictures that are loaded from the folder "gallery".

    That's all about attribute selectors. All of the above methods can be combined with each other:

    Selector[attribute1="value1"][attribute2="value2"] ( style )

    In addition, let me remind you about special CSS selectors:

    • using the symbols “+” and “~” are formed;
    • the ">" symbol binds css styles to subsidiaries tags;
    • symbol<пробел>generates context selectors.

    In future articles we will also look at pseudo-elements and pseudo-classes that provide powerful tool style management.

    That's all, see you again.

    CSS - Cascading Style Sheets.

    Attention! You do not have permission to view hidden text.


    World CSS- this is a magical world of endless combination of properties and appearance(styles) -objects and elements. And the most important thing actor at this "celebration of life" CSS is CSS selector.

    Selectors in CSS - terms and definitions

    As you know, styles (appearance and properties) of elements
    there may be , and .

    Built-in styles Built-in styles are specified directly in HTML tags and are, perhaps, the easiest way to use them. The effect of inline styles applies exclusively to the HTML element in whose opening tag it is inserted (embedded). For example, here's the code: text- will create a red background only inside the span element and nothing more. Result - text Internal styles Internal styles are specified as stand-alone code, which can be located in source code web pages, wherever he pleases - at the beginning of the page, at the end or in the middle. Example internal style code:
    External styles Most difficult option- these are external styles. When using external styles, the code for each style is written in an external file with the “.css” extension. There can be several such files and they can be located anywhere, even on another site.

    Unlike the inline style, the action of the code is internal and external styles applies to the entire web page at once. In this case, on the field of the web page itself there may be great amount various similar HTML elements. To tell the browser exactly which element a particular style belongs to, CSS technology uses classes, pseudo-classes, identifiers, and selectors. Thus, a "CSS selector" is a utility symbol for describing an element or group of elements to which a specified style rule applies.

    Note To be fair, it should be noted that things like classes and identifiers belong more to HTML code than to CSS styles. And only “CSS selectors” and pseudo-classes are truly CSS developments. Which is exactly what we're talking about.

    Selector in CSS - “thinking along the tree”

    Based on the above, for myself personally, I defined the concept of the term “selector in CSS” as follows:

    "selector in CSS" is a service sign that tells the browser where and how to apply the specified HTML element style.

    As in ordinary life, it just means a banal selection of an HTML element for subsequent assignment of a style (appearance, properties, etc.).

    Why do you need a selector in CSS?

    A selector in CSS is a kind of connecting link between CSS and HTML codes. By setting the selector (by selecting an element), we indicate to the browser the location, object and rules for applying the specified CSS properties (styles). To move from nerdiness to practice, it would probably be appropriate to remember life in CSS without selectors.

    Global Properties in CSS
    (life without selectors)

    Life without selectors is possible! But is this life? Without selectors, Cascading Style Sheets (CSS) lose their meaning completely. Firstly, it is possible to write only the name of a real tag from a real existing specification into a class name without a selector. Secondly, such a record will apply to absolutely all tags with the specified name on the HTML page that can only be found there.

    For example, a record like:

    A(background:#000;) - will paint all links on the page black table(background:#000;) - will paint all tables on the page black div(background:#000;) - will paint all blocks black ( divs) on a web page, etc.
    In short, all specified CSS styles and properties will be applied not selectively, but globally, spreading their effect to all page tags at once...

    Of course, such a recording without selectors has its own charm. After all, this is how CSS declares global styles for all HTML objects. The most common example of declaring global properties is cross-browser reset of indentations (margins and paddings). Its CSS code looks something like this: html,body,div,ul,li,dl,dt,h1,h2,h3,h4,h5,h6(margin:0;padding:0;), although there may be other options. Another popular example of global settings (styles) that affect all HTML objects on the page is cross-browser formatting of new ones: header,section,footer,aside,nav,article(display:block;). Here, again, other options are also possible.

    However, in any case, all these will be global CSS styles set for the entire web document - properties that apply to absolutely all specified tags and elements HTML pages. But to CSS settings affected only the specified desired element or group HTML elements- required selector.

    What is a selector in CSS

    Let's summarize.

    First. The code of the HTML element itself and its style code can be located in different places on the web page, site, and even on different sites.

    Second. To identify an HTML element, it is given a class or identifier, the code for which is added to the HTML element's code.

    Vlad Merzhevich

    Elements of a web page are called adjacent when they immediately follow each other in the document code. Let's look at a few examples of element relationships.

    Lorem ipsum dolor sit amet.

    In this example the tag is a child of the tag

    Because it is inside this container. Respectively

    Acts as a parent .

    Lorem ipsum dolor sit amet.

    Here are the tags And do not overlap in any way and represent adjacent elements. The fact that they are located inside the container

    Doesn't affect their attitude at all.

    Lorem ipsum dolor sit amet, consectetuer adipiscing elite.

    Neighboring tags here are And , and And . Wherein And adjacent elements are not treated because there is a container between them .

    To control the style of adjacent elements, use the plus symbol (+) between two selectors. General syntax next.

    Selector 1 + Selector 2 (Description of style rules)

    The spaces around the plus are optional; the style in this notation is applied to Selector 2, but only if it is adjacent to Selector 1 and immediately follows it.

    Example 11.1 shows the structure of how tags interact with each other.

    Example 11.1. Using adjacent selectors

    HTML5 CSS 2.1 IE Cr Op Sa Fx

    Adjacent selectors

    Lorem ipsum dolor sit amet, consectetuer adipiscing elite.

    Lorem ipsum dolor sit amet, consectetuer adipiscing elite.

    The result of the example is shown in Fig. 11.1.

    Rice. 11.1. Highlighting text with color using adjacent selectors

    IN in this example the text color for the contents of the container changes when it is located immediately after the container . In the first paragraph, this situation is implemented, so the word “consectetuer” is displayed in red in the browser. In the second paragraph, although there is a tag , but no tag in the neighborhood no, so no style is applied to this container.

    Let's look at a more practical example. It often becomes necessary to include various footnotes and notes in the text of an article. Typically, a new style class is created for this purpose and applied to the paragraph; in this way, you can easily change the appearance of the text. But we'll go the other way and use adjacent selectors. To highlight comments, we will create new class, let's call it sic and apply it to the tag

    . The first paragraph after such a heading is highlighted with a background color and indentation (example 11.2). The appearance of the remaining paragraphs will remain unchanged.

    Example 11.2. Change paragraph style

    HTML5 CSS 2.1 IE Cr Op Sa Fx

    Change paragraph style

    Methods for catching a lion in the desert

    Sequential search method

    Let the lion have dimensions L x W x H, where L is the length of the lion from the tip of the nose to the tassel of the tail, W is the width of the lion, and H is its height. After which we divide the desert into a number of elementary rectangles, the size of which coincides with the width and length of the lion. Considering that the lion may not be strictly in a given area, but at the same time in two of them, the cage for catching should be made of a larger area, namely 2L x 2W. Thanks to this, we will avoid the mistake of only half the lion being caught in the cage, or, worse, only its tail.

    Important Note

    To simplify calculations, the tail can be discarded and not taken into account as a measurement error.

    The result of this example is shown in Fig. 11.2.

    Rice. 11.2. Changing the appearance of a paragraph by using adjacent selectors

    In this example, the text is formatted using paragraphs (tag

    ), but writing H2.sic + P sets the style only for the first paragraph following the tag

    , which has a class named sic added.

    Adjacent selectors are convenient to use for those tags to which indents are automatically added in order to independently adjust the amount of indentation. For example, if there are tags in a row

    And

    , then the distance between them can be easily adjusted using adjacent selectors. The situation is similar for consecutive tags.

    And

    And also in other similar cases. Example 11.3 changes the amount of space between specified tags in this manner.

    Example 11.3. Spaces between headings and text

    HTML5 CSS 2.1 IE Cr Op Sa Fx

    Adjacent selectors

    Heading 1

    Heading 2

    Paragraph!

    Since when using adjacent selectors, the style is applied only to the second element, the size of the margins is reduced by including a negative value for the margin-top property. In this case, the text rises up, closer to the previous element.

    Questions to check

    1. Which tags in this code are adjacent?

    Sulfuric acid formula:H 2 SO 4

    1. AND

    2. And
    3. And
    4. And
    5. And

    2. The following HTML code is available:

    Fermat's Last Theorem


    X n+Y n
    = Z n


    where n is an integer > 2

    What text will be highlighted in red using the SUP + SUP ( color: red; ) style?

    1. Second "n"
    2. Second and third "n".

    Today we'll 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 to CSS properties. The word "selector" is self-explanatory; it means 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 - p, div span, ul li. That is, our entire style file consists of selectors and their properties. It is most convenient and intuitive, especially for beginners, to use the class name of the tag or the unique identifier of the tag as the selector. To assign a class or identifier to any tag, we must specify it among the attributes of that tag. A specific tag can have a maximum of 1 ID and infinite number classes. Example:

    text in first div
    text in second div
    text in third div

    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 a page.
    • If we want to assign several classes to a specific tag, we simply specify them separated by a space.
    • The names of classes and identifiers can be the same, but apart from the name, there will be nothing in common between them.

    How to refer to a class or id in a stylesheet (CSS) file?

    Let's look at an example:

    #first (color: red;) /* access the id named first */.second (color: blue;) /* access the class named second */#first .second (color: orange;) /* access the class named second ONLY if it is INSIDE the tag with identifier first */.first .third (color: grey;) /* refer to the 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 specifically to id, we need to put a hash sign (#) in front of its name without spaces; if we are referring to a class, then we must put a dot (.) in front of the class name.

    Using classes and identifiers is very convenient, but it increases our HTML markup, ideally (which never exists) we should not 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 should 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 specified by id have a higher priority than properties assigned to the class. That is, if we write:

    text in diva

    Then the text color will become red, despite the fact that the class is lower in the code and if they had equal priority the text would turn blue.

    According to the 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 the class myclass */ div.myclass (properties) /* will only apply to div tags that contain the class myclass */

    This will also work for id, but such an entry is meaningless, since id cannot be repeated on the page, which means it is enough to simply declare the id without the tag to which it refers:

    text

    It seems that there is only one unspecified difference left, and it concerns a topic that I did not plan to touch on in the near future on this blog - Javascript. But I am still obliged to report it to you: if you want to access 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 will have to use secondary functions+ it's not always cross-browser compatible.

    Bottom line: we use id and class, but in moderation, always asking ourselves whether it is possible to do without them and how advisable it is.

    Related selector

    Div p (color: green;) /* Selector by child */ p(color: red;) /* selector by tag */

    But as I already wrote in the previous article, in the first case, CSS properties will be applied to all p tags nested at ANY depth of the div tag. But what if we want to apply properties only to direct descendants, that is, to the first level of nesting:

    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 or you can leave them out, I would not recommend it:

    Div>p (color: blue;) /* only the first level of nesting */ div p (color: blue;) /* absolutely all paragraphs inside a div */

    Universal selector

    We've sorted this out, we already have 3 types of selectors in our arsenal, now I want to tell you about a very unusual selector that stands out among all the others - this is the so-called universal selector, which is indicated by an asterisk (*):

    * (margin: 0; padding: 0;)

    This is how everyone starts for me new project, I advise you to do the same. The universal selector applies to all page elements (tags), but has zero priority (below only no priority at all). It is commonly used to override the CSS properties that browsers set by default for some tags. Imagine, this actually happens! Browsers set their own properties for quite a few tags by default, for example, the hyperlink tag blue text color and underlining, they set padding to the body tag, etc. There is absolutely no need for us to remember, know and use this, so we immediately remove the most banal properties using a universal selector, however, I would not recommend adding anything else to it (or adding, but carefully), despite the smallest (null ) priority of the universal selector, in some cases it can still override other properties for you, so keep that in mind.

    By the way, when working with selectors, as with any work related to layout layout, it is very convenient to use viewing page elements. If you are not yet aware of such things as Opera Dragonfly, Firebug and web inspectors in general, then, without exaggeration, you urgently need to read the article at the link above! And whoever has already used similar things, please follow me.

    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 ones 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 selectors as you wish, for example:

    Div>span p:first-child (color: green;) /*will work if p is the first child of its parent and is inside a span tag that is a direct child of a div tag */

    The name of the pseudo-class presented above speaks for itself first-child - the first child.

    The following two static pseudo-classes apply only to the hyperlink tag (:link, :visited), they apply CSS properties depending on whether the this link specific user or not:

    A:link (color: blue;) /* set the color blue for unvisited links, and by default they are underlined */ a:visited (color: green; text-decoration: none;) /* visited links will have red text, remove the underlining */

    The pseudo-class:lang() is used to provide different styling depending on the language. The language to which the design should be applied is indicated in brackets. This can be used, for example, to set different styles quotation marks in quotations:

    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 language */

    This is perhaps the only possible type of selector 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 when you click 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). IN in this case upon focusing, the width of the input will become equal to 400 pixels, convenient to use for beautiful effect Extend the field by clicking. */ div:hover (background: green;) /* Triggered when the cursor hovers over an element, mainly used to create a beautiful effect when hovering over links. */

    Apply these styles to our example above and you will see for yourself.

    Adjacent selectors

    Adjacent selectors are the nearest neighbor below the code, not the child! Very convenient selector:

    text in paragraph of first div

    text in paragraph OUTSIDE div

    text in paragraph of second div

    text in span

    again the paragraph is outside the div

    Result:

    Generalized adjacent selectors

    Generalized adjacent selectors act exactly like regular adjacent selectors, except that the properties apply not just 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 access tags that have the 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 at center */ p (properties) /* where the value of the align attribute contains center */ p (properties) /* where site can be 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 become familiar with all the main selectors and this should be enough for you in the first couple of days. However, in CSS 3, many new pseudo-classes have appeared, now we can take not only the first child, but also any other child, 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, except that you may have problems with older versions of IE. Let's gather all our strength and go through all the remaining selectors, so that later you can keep them in mind when creating your own layout.

    :last-child – analogous to:first-child, but takes not the first, but the last child.

    :only-child – will work if the element (tag) is the only child.

    :only-of-type - will work if the element (tag) is the only child of its type.

    :nth-child() – refers to children by their serial numbers, you can access all 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 that do not contain a single character (no text).

    :not() – throws an exception for the given elements. Example:


    paragraph with class roll


    paragraph

    paragraph


    paragraph with class roll

    Result:

    Managing fields, forms, radio buttons, and checkboxes in CSS

    :enabled - applies to accessible interface elements such as forms, buttons, switches, etc. By default, all interface elements are accessible.

    :disabled - applies to disabled interface elements such as 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 radios and checkboxes when they are in the on position.

    Pseudo-elements

    Pseudo-elements, similar to pseudo-classes, are calculated automatically by the browser; we don’t need to worry about this. To avoid confusing pseudo-elements with pseudo-classes in CSS specs 3, it was decided to use a double colon, instead of a single one, as was the case in CSS 2. Therefore, on the Internet you can find pseudo-elements with both a single colon and a double colon - both options are correct. However, for better compatibility with IE, it is recommended to use a single colon.

    :first-line – the first line inside a block or table element.

    :first-letter – 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 create website layouts using as many selectors, pseudo-classes and pseudo-elements as you have learned today. I have listed all the possible tools, and you should choose only the most necessary for yourself.

    Benefits of optimizing HTML with CSS

    Part of the point of all of the above is to move away from the ubiquitous use of class and id attributes in HTML, thereby leaving everything to the mighty style sheets.

    External style files, like external Javascript files are perfectly cached, which means that when visiting any page of your site for the first time, the user’s browser remembers these files and does not download them again, unlike the site page itself, that is, your HTML markup, pictures and text, which the browser downloads again and again. The same goes for search engines, they don’t care about yours at all. external files, but they don’t care about the volume and content of your HTML markup. Search engines you have to scan the entire structure of the page and it is in your best interests to help them with this, to focus their efforts on the content, and not on a cumbersome wall of markup consisting of a bunch of classes and identifiers, or 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 local environment all included 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, without losing anything except a possible habit.

    Let's summarize: thanks to optimization and reduction of HTML, we have a very small gain in site loading speed and SEO ( search engine optimization), as well as cleaner code.





    

    2024 gtavrl.ru.