CSS selectors are lowercase. Selectors in CSS. Which tags in this code are adjacent?

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 in various ways as you see fit. 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

    Let's say you want to apply a style rule to a certain element only when it is inside 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 the following 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 a direct child of the 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 that have a type attribute with the value text:

    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 ids together as shown below:

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

    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) of objects and elements. And, the most important character in this “celebration of life” CSS is CSS selector.

    Selectors in CSS - terms and definitions

    As you know, styles ( appearance and properties) -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 the source code of a web page wherever it pleases - at the beginning of the page, at the end or in the middle. Example internal style code:
    External styles The most difficult option is external styles. When using external styles, the code for each style is written in an external file with the extension “.css”. There can be several such files and they can be located anywhere, even on another site.

    Unlike an inline style, the effect of the internal and external style code is applied 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 specified name on the HTML page, which 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 in different places web page, site and even across 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.

    Igor. Update: October 30, 2018.

    The starting article of this section provided general information regarding, including a description of how to connect styles to the HTML code of a website page (document), which determines the presence of certain elements on a web page.

    In this publication, we will look at how to correctly compose and write CSS properties for all elements so that the browser can identify them and display them correctly on the page.

    In particular, let's look at what a single style rule is in general, which includes a selector, as well as properties and their values.

    Syntax and options for writing CSS rules

    Since cascading style sheets are, albeit a specialized, but still a language, it is permissible to draw an analogy between a set of CSS rules and simple text, where each word consists of letters, a sentence consists of words, and text fragment- from proposals.

    Given this visual association, we can derive a logical sequence that concerns the CSS structure (it is the most optimal, in my humble opinion):

    • values ​​(or parameters), which is expressed in numbers, color code, font name, etc., in accordance with our analogy, can be considered letters;
    • structural CSS unit is property, which defines its part of the appearance of an element on the page (its color, text font, size, indents, position, etc.), to which specific values ​​(one or more) correspond. Here, the combination of a property name and its parameter can be compared to a word (which can also consist of one or more letters) in a standard text fragment;
    • CSS rule - selector(style name) along with set of CSS properties for each element it completely determines its design and location on the page. Structurally associated with a sentence (a set of individual words in ordinary text);
    • a complete collection of all CSS rules for a specific document (web page) ensures its correct display in the browser. Let's compare this with a completed passage of text.

    Perhaps the association I proposed is a little far-fetched, however, it seems to me that it will still help beginners understand general structure CSS language.

    So, each property is assigned a specific value (parameter), and there may be several of them. The corresponding set of properties (rule) is applied to a specific selector. Schematically, a CSS rule can be displayed like this::

    A selector is placed in front, then curly braces (opening and closing) are placed, between which there are CSS properties with their assigned values, the name of each property is separated from its corresponding parameter by a colon. All properties along with their values ​​are separated by a semicolon. Let's look at a live example:

    Body ( font-size: 14px; background: #00ff00 url("west.png") repeat-x; )

    Please note that the background property has several values: background color (#00ff00), path to background image(“west.png”) and the resolution to repeat it horizontally (repeat-x). You probably noticed that this recording option is somewhat different from the diagram presented just above.

    In fact, there is no inconsistency here. Since CSS is not sensitive to spaces, line breaks, or tabs, style rules can be written in the most different ways, which are used in specific situations.

    For example, an extended rule entry, a sample of which has just been presented, is the most convenient for perception, and therefore is usually used for studying styles, or in the “raw” style.css file, which was created for a new site and therefore has not yet been finalized . There is another variation of this same option CSS entries rules:

    Body ( font-size: 14px; ) body ( background: #00ff00 url("west.png") repeat-x; )

    As you can see, the same selector is repeated for each property. This is not an error for the reasons mentioned above, but this format for writing a rule clutters the code and complicates its perception, and therefore is practically not used.

    An extended version of the notation can be presented without hyphenation:

    Body ( font-size: 14px; background: #00ff00 url("west.png") repeat-x; )

    But that's not all. All spaces, as well as the separating character (semicolon) after the last property (before the closing curly brace), can be omitted. This is also quite legitimate CSS shape rules, less voluminous, which is good for site optimization, but less readable:

    Body(font-size:14px;background:#00ff00 url("west.png") repeat-x)

    After the site design is ready and everything is entered necessary changes in CSS style files, they are adjusted accordingly in order to optimize the web resource, while all spaces are automatically removed. This can be done manually, but why waste precious time so irrationally? After all, even for a small site, the style.css file can contain many style rules.

    Selectors, Properties, and Applying Styles

    I have already noted that over time there is an increasingly closer convergence of HTML and CSS. If at the dawn of the Internet in its current form, the appearance of elements on a web page was described using the attributes of hypertext markup tags, today too frequent use This method is considered since overloaded HTML code often does not contribute to proper optimization of site pages, which also harms its SEO promotion.

    Block with green text surrounded by a frame

    CSS (the identifier is preceded by a hash icon):

    #area (color: green; border: 2px solid #d6c99a)

    The following options can contain both tag selectors and classes with identifiers.

    Why are these sizing options needed? The fact is that it is not always the best solution is the use of standard relative values, including interest. Sometimes it is more beneficial to link the font size to the height and width of the browser window. Let's say, if the viewport height is 800px, then 1vh = 8px, and if the width is 1500px - 1vw = 15px.

    The units vmin and vmax are determined by the minimum and maximum dimensions areas in height and width. Sample: Browser window height is 700px and width is 1300px. In this case vmin = 7px and vmax = 13px.

    When setting dimensions, you must specify the units (for example, height: 55px), otherwise the browser will display the corresponding elements incorrectly. Meanings, equal to zero, To this rule do not apply, they can be designated in two ways (padding: 0 or padding: 0px), for obvious reasons, the first option is in the lead with an overwhelming advantage.

    Interest

    I decided to mention this type of units separately. Above I already talked about the advantage of using relative values ​​when setting properties. This fully applies to interest.

    Table (width: 100%; /* Table width in percentage */)

    Percentage entries are used quite often, especially when it is necessary to set the value relative to the parent or when the sizes depend on certain external circumstances. For example, an element width equal to 100% will adapt to the most screens. different devices and display correctly there.

    Keywords

    Let's look at some words that play the role of property parameters and determine one or another position or appearance of an element. Here are some illustrative examples.

    1. Text-align property values, which help align text horizontally: center | justify | left | right | start | end. Here is an example with the parameter justify:

    P (text-align: justify)

    This notation means that the paragraph text is aligned both left and right:

    2. CurrentColor- matches the value of the color property of the current element and specifies a color for areas that do not receive one by default. Let's say a container with class "bl-2" is nested in "bl-1":

    The currentColor value specifies the background color

    And styles are specified for both:

    Bl-1 ( padding: 10px; /* Margins around the inner container */ background: currentColor; /* Background color */ ) .bl-2 ( color: blue; /* Text color */ padding: 10px; /* Margins around text */ background: #ccc; /* Background color */ )

    If there is no text color specified for an element (the “color” property), then by default the text fragment will be colored black (in most popular browsers). In our example, for the outer container (“bl-1”) color is missing. As a result, when specifying the “currentColor” value, the background of this container will become black:

    3. Inherit- This keyword as a parameter of the corresponding values ​​of parent elements. Sample:

    The inherit value determines the inheritance of properties

    And the CSS rules for it:

    Bl-1 ( border: 4px solid red; padding: 10px; ) .bl-2 ( border: inherit; padding: inherit; )

    As a result, the border design and padding were moved from the parent block (bl-1) to the internal block (bl-2):

    4. Initial— used in cases where it is necessary to set the initial parameters of properties. Let's say it helps to restore values, installed by browser by default, or define initial parameters, which have been changed as a result of inheritance. Example:

    CSS Property Options

    There are a wide variety of meanings that determine certain styles, which determine the appearance of elements on a web page.

    Read more details

    And styles for it:

    H2 ( color: #2e15d1; font-family: Verdana, sans-serif; ) p ( color: green; ) .init ( color: initial; font-family: initial; )


    Using the "init" class, the appearance of the p paragraph fragment enclosed in the span tag and the H2 bottom header are changed to match their default styling settings.

    5. Unset is a parameter that is essentially a “hybrid” of inherit and initial. Defines the property parameter as inherit if the property is inherited from a parent, otherwise as initial.

    Example 1(acts like inherit):

    Text color green - inherits the value of the "color" property for the "zzz" class

    The text color is red according to the value of the "color" property for the p tag

    P (color: red) .zzz (color: green) .xxx p (color: unset)

    According to CSS rules the color property is inherited, so "unset" in our example returns green color text for the container "xxx" which is a child of "zzz":

    Example 2(works like initial):

    Frame color is black - default value

    The border color (blue) is set in the properties of the div container

    Div ( border: 2px solid blue; margin-bottom: 10px; margin-top: 10px; padding: 10px; ) .xxx ( border-color: unset; )


    Since according to the rules of style sheets border property is not inherited, then “border-color: unset” returns the border color to its default value, that is, it becomes black.

    URL or address

    This parameter contains and is used when you need, for example, to point to a file with an image (read with using HTML img tag). In this case it is used keyword url(), where between the brackets and the path to the graphic file is indicated:

    Body ( background: url(https://site/images/star.jpg) no-repeat; /* Absolute path */ ) div ( background: url(images/globus.jpg) no-repeat; /* Relative path * / )

    Time

    It is used, for example, when implementing animation effects (yes, on pure CSS you can now create such things), where the parameters are specified in seconds (s) or milliseconds (ms). Values ​​can be either integers or fractional numbers. At the same time, we must remember that there should be no space between the number and the unit of measurement (2s, 50ms)./p>

    Let's look at an example.

    And, accordingly, styles for it:

    Loading ( width: 440px; margin: auto; padding: 20px; background: #c49746; color: #fff; text-align: center; ) .spin ( display: inline-block; width: 70px; height: 70px; border: 10px double #ccc; border-right: 10px double transparent; border-radius: 70px; /* Animation */ animation: spin 5s linear 0s infinite normal; 0deg); ) to ( transform: rotate(360deg); ) )

    On this page You can not only look at the result, but also try to edit some properties, so to speak, in practice, in general, experiment. Naturally, it is still difficult for beginners to study cascading style sheets to understand and take into account the subtleties of animation, but a continuation will definitely follow, so be sure to subscribe to fresh materials in order to get what you want on time. But let's continue.

    Strings

    This type of option allows you to add text fragments. Strings must be enclosed in quotes (single or double). Moreover, if you need to put a word or phrase in quotes inside a string, then these types of quotes can be combined.

    For example, if you put the entire line in single quotes, then the internal text fragment is in double quotes, and vice versa. It is also allowed to use the same type, only in this case it is necessary to escape the internal quotes by adding a backslash “\” in front of them:

    • property: "string 'content'"
    • property: "string 'content'"
    • property: "string\"content\""

    To get started, the HTML code:

    Current version articles.

    And now the styles:

    New::after ( content: "updated"; color: red; )

    Color

    Various parameters can be used to indicate colors for properties when writing CSS rules. Let's look briefly at each of them:

    1. Name. True, not all shades can be specified in this way, but only some of the shades (“red” - red, “green” - green, “black” - black, “orange” - orange, “yellow” - yellow, “olive” - olive and some others). They can also be classified as keywords.

    P (color: green)

    2. Hex ( hexadecimal code) . The basis of the hexadecimal system, in contrast to the well-known decimal system, is 16 characters: 10 numbers (from 0 to 9) and the first 6 letters of the Latin alphabet (A, B, C, D, E, F). Letters A to F correspond to numbers 10 to 15.

    P (color: #f8f9e3)


    3.1. RGB— you can set the color value based on the decimal system. Name this method is an abbreviation for the three main colors involved: R ed (red), G reen (green), B lue (blue). The shades of each of them are in the range from 0 to 255. To use this system, you need to write rgb in front, and indicate each of the color components in brackets: rgb (240, 0, 180). It is also possible to use percentages:

    Div ( background-color: rgb (210, 0, 90); color: rgb (100%, 50%, 15%); )

    3.2. RGBA- An extended version of the previous RGB method, it contains an alpha channel that sets the transparency of the element in the range from 0 to 1. The parameter "0" is fully transparent, and "1" is completely opaque.

    Body (background-color: rgba (255,255,255,.9))

    4.1. HSL— the name of this method is also nothing more than an abbreviation that includes the first letters of three words: H ue (hue), S ataturate (saturation) and L ightness (lightness). It is these characteristics that together determine the final color. In this case, the shade is located at a specific place on the color wheel:

    Since the entire circle is 360°, each hue (hue) corresponds to a very specific value in degrees ranging from 0° to 359°. In this case, the parameters of the main shades are as follows: 0° - red, 120° - green, 240° - blue.

    Saturation and lightness are measured as percentages (from 0 to 100%). For saturate, parameter 0 means none color range, and 100% is the maximum saturated color. How more value lightness, the lighter the tone, 0 corresponds to black, and 100% corresponds to white.

    Div (background-color: hsl(40,90%,15%))

    4.2. HSLA- similar to RGBA, it is an extended version of HSL, to which a transparency indicator is added.

    Div (color: hsla(120,100%,50%,0.6))

    Angle of rotation or tilt

    In CSS, angular characteristics (based on a circle) can be used as parameters for certain properties. Here are the units used:

    • degrees - deg(1 full circle is 360deg);
    • grads - grad(full circle 400grad);
    • radians - rad. A whole circle is equal to 2π (approximately 6.2832rad);
    • turns - turn(1 turn is equal to a full turn).

    It is important to note that negative values ​​can be used. Below are illustrative examples with parameters of some angles (rotations):


    For clarity, let’s use the rotation characteristics to implement gradient fill background and as one of the components of our sample, we will place certain text on the page:

    Gradient background fill.

    Now let’s create a CSS rule for this background:

    Body ( background: #f5e573; background: linear-gradient(-5deg, #f5e573, #f7f4db 50%, #f7f6eb); )

    You can evaluate the result at this page and practice there, editing the styles as you wish. This will also be useful for acquiring practical skills.

    In the last lesson we looked at ways CSS connections. Now let's move on to the language itself.

    Like any other language, CSS has its own, but extremely simple syntax. Consists of only two components:

    1. Selector(selecting the object we will work with. For example, title, div, table, etc.)
    2. Style block- description of one or more properties of an object - color, size, etc. Consists in curly braces ()

    We see how the title is a selector; in the style block, the text color property is assigned ( color) - blue.
    Style block comprises properties And their meanings, which are separated when enumerated semicolon (;), as in the example below.


    Now we're adding one more property - text formatting (font). In it we give meaning text size - 20 pixels.

    Example of CSS in action

    Create a folder anywhere, for example, lesson 2. Create a file in it style.css. Copy all the code below into it. In the CSS code we set properties for the tag and headings

    And

    .

    CSS code(file style.css)

    Body(
    background: gray;
    color: white;
    }
    h1(color:#0085cc;)
    h2(color:white;)
    Please note that there will be no difference whether the style block is written in a line (h1,h2) or in a column (body). Both options will work. Choose what suits you best.

    Now let's create an HTML file. It doesn’t matter what the name is, the main thing is that the path to the file with the CSS code is specified correctly. Indicated in the same way as in links, paths to images. The example below shows the path (style.css) to the same directory as the html file. That is, both files must be in the same folder.

    HTML code



    Example of CSS in action



    Heading h1


    Heading h2



    The result of the code can be seen at the link below.

    CSS selectors

    In the examples above, the selectors were page elements: body, h1, h2. However, there are situations when you need to work with a specific element, and not all. For example, all the headings were blue, and one at the end was black. There are different types of selectors for this. Let's take a closer look at them.

    Identifiers

    Item ID is a selector that is assigned to one element and makes it unique. Set using parameter id.

    This paragraph is assigned an id. It will have unique properties.


    The text options will remain at their defaults.


    Let's look at an example

    HTML and CSS code



    Example of CSS in action



    Text that will be blue because there is an id


    The text color will remain at its default.



    First, in the styles of all paragraphs, the color property is set to black, and the text of the paragraph with id "blue" will be blue. Selector in in this case consists of an element (p - paragraph), a separator (# - identifier designation) and the identifier name (blue).

    It is important to note that in theory the identifier is given to only one element to which we want to give unique properties. Yes, in some browsers, giving the same ID to two elements may work. However, this will not happen everywhere.

    If you want to set styles for several elements, you should use classes.

    Classes

    Class is a selector that allows you to apply styles to one or more elements. For example, id only applies to one unique element. The value is the name of the element.

    Let's look at an example:

    HTML and CSS code



    Example of CSS in action



    Text color is black.



    Blue text.


    The text is bold and blue.


    Text color is black.



    As a result, the paragraph with the identifier ( id) blue will have blue text, elements with class blue will be highlighted in bold and blue. And all other elements p will have a black font.

    As you can see, the class can be applied several times. Accordingly, all elements will have the properties described for this class.

    Unified selectors

    Unified selectors (.) is a selector that can be assigned to different types of elements, for example, headings, paragraphs, and blocks (divs). The most common option. Previously, we used the construct in the CSS code p#blue And p.blue, that is, first they indicated the type of element (p - paragraph), and then the identifier or class itself. So you can specify the construction more simply, start right away with .blue. A similar selector will be applicable not only to paragraphs, but to other elements.

    HTML and CSS code



    Example of CSS in action



    Header with identifier.

    Text color is black.


    The text is bold and blue.


    The text in the block is also bold and blue

    Text in inline element also bold and blue



    The result is a unified selector, in this case class .blue, we applied to both a paragraph (p), a block (div), and a line element (span). The result is the same everywhere - the text is bold and blue.

    Context selectors

    Context selector is a selector that selects one element in a group of other elements. The spelling is marked with a space. To make it easier, let's move straight to an example. Let's say we want the bold text contained in paragraphs to be highlighted in some other color.

    HTML and CSS code



    Example of CSS in action


    Text color is black. But bold font tags are not mentioned here.


    Regular bold text, which is not contained in the paragraph. Therefore, its color does not change.

    And attention!!! Paragraph with a phrase bold blue font



    Accordingly, only the bold text (strong) that will be in paragraph (p) will be highlighted in blue.

    Grouping selectors

    Grouping selectors- this is a style sheet construction where the style declaration block addresses one or more previously mentioned elements and adds a new property.

    The text is difficult to understand. It’s better to take an example right away.

    H1, h2, h3( color:blue; )
    h1(font-size:18px; )
    h2(font-size:16px; )
    h3(font-size:14px; )
    In the first line we immediately mention several elements. In order to access several elements at once, you need to list them in the selector using the sign , (comma) and space. There is NO need for a comma or space before the last item to be enumerated..

    By subsequent mentions of these elements, we add new property values ​​to them. In this case, font size.

    HTML and CSS code



    Example of CSS in action


    Heading h1


    Heading h2


    Heading h3



    As a result, all headings will be blue. However, different sizes, because subsequent entries in the style sheet gave the headings different sizes.

    The use of grouping is a controversial issue. Among benefits It can be noted that it is possible to avoid large parts of the code, which will largely duplicate themselves in content. Among the disadvantages, we can say that using such code, where properties are added to one or another element in different places, is quite problematic and inconvenient. Of course, with proper sequential writing you can avoid such disadvantages, but that’s another question.

    Thank you for your attention! The lesson is over!


    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're 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 to ANY depth 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 I start every new project, and 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, body tag they set the fields (padding) and so on. 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 link has been visited by a particular 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 specify 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 specify different styles of 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 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 certain action on the page, they work for all tags, and not just for links, as many people think and even claim on 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 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 ordinal 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() – makes an exception for 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. In order not to confuse pseudo-elements with pseudo-classes in the CSS 3 specification, 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 that option is 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 putting everything on the shoulders of 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 anymore, unlike the site page itself, that is, your HTML markup, images and text that the browser downloads again and again. The same applies to search engines, they don’t care at all about your external files, but they do care about the volume and content of your HTML markup. Search engines have to crawl the entire structure of the page and it is in your best interest to help them do 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 all connected files, images into its local environment, 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.

    To 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.