Selectors in CSS. CSS Property Options
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 the set of CSS rules and in plain text, where each word consists of letters, a sentence consists of words, and the text fragment itself consists of sentences.
Given this clear association, we can deduce logical sequence, which 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;
- The structural unit of CSS 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 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, but I think it will still help beginners understand the general structure of the 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: the background color (#00ff00), the path to the 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 a variety of ways to suit 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 CSS rule entry:
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)
Once the site design is ready and all necessary changes have been made to the CSS style files, they are adjusted accordingly in order to optimize the web resource, and 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 appearance elements on a web page were described using hypertext markup tag attributes, these days it is 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.
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 percentages. 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. Values equal to zero do not apply to this rule; they can be designated in two ways (padding: 0 or padding: 0px); for obvious reasons, the first option is overwhelmingly in the lead.
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. Values text-align properties , 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":
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 is a keyword as a parameter of the corresponding values of parent elements. Sample:
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 default, or define initial parameters that were 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)
In accordance with 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 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 an image file (read 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, you can now create such things using pure CSS), 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; ) /* Set rotation */ @keyframes spin ( from ( transform: rotate( 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 of the article.
And now the styles:
New::after ( content: "updated"; color: red; )
Color
CSS can be used to indicate colors for properties when creating CSS rules. various parameters. 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). basis hexadecimal system, unlike the well-known decimal, there are 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- extended version previous method An RGB containing an alpha channel that sets the element's transparency, ranging from 0 to 1. A value of "0" is completely 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 no color range, and 100% is the most saturated color. The higher the lightness value, the lighter the tone, 0 is black and 100% is 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, we will use the rotation characteristics to implement a gradient fill of the 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.
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 a direct child of the element
. Other paragraphs placed inside other type elementsorAdjacent 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; )
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 to which we are going to apply 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 divtext in second divtext in third divWhat 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 divaThen 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:
textIt 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 still have to tell you about it: if you want to access an element using Javascript, then having an id for this element will be very convenient for this purpose. 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 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, 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 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 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 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 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 that currently has 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 a beautiful effect of lengthening 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
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 divaparagraph
paragraph
paragraph
text in spanparagraph
paragraph
paragraph in diva
paragraph in diva
text in spanparagraph
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 spanparagraph
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. 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 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 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 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 directly in 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.
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
The 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 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 windowResult:
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%;
}
...
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 differently. External links always start with the string "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, different graphic image formats can be displayed differently. 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 the 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'll also look at pseudo-elements and pseudo-classes, which provide powerful style management tools.
That's all, see you again.
What is a selector in css is a description of that element or group of elements that tells the browser which element to select to apply a style to it. Let's look at basic CSS selectors.
1) .X
.topic-title ( background-color: yellow; )CSS selector by class X. The difference between id and class is that several elements on a page can have the same class, but id is always unique. Classes should be used to apply the same style to multiple elements.
- Chrome
- Firefox
- Safari
- Opera
2) #X
#content ( width: 960px; margin: 0 auto; )CSS id selector. The hash sign before the CSS selector X selects an element whose id = X. When assigning styles by id, you should always remember that it must be unique - only one such id should be on the page. Therefore, it is better to use selectors by classes, combinations of classes, or tag names. However, id selectors are great for automated testing because... They allow you to immediately interact with exactly the desired element and have confidence that there is only one of its kind on the page.
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
3) *
* ( margin: 0; padding: 0; )CSS selector for all elements. The star symbol selects all elements that are on the page. Many developers use it to remove (zero) the margin and padding values of all page elements. However, in practice it is better not to do this because this CSS selector loads the browser quite heavily by searching through all the elements on the page.
The * symbol can also be used to select all child elements:
#header * ( border: 5px solid gray; )
This example selects all children (descendants) of the element with #header . But it's always worth remembering that this selector is quite heavy for the browser.
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
4) X
a ( color: green; ) ol ( margin-left: 15px; )CSS type selector. How to select all elements of the same type if they have neither id nor classes? It is worth using a CSS element type selector. For example, to select all ordered lists on a page, use ol(...) as shown above.
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
5) X Y
li a (font-weight: bold; text-decoration: none; )CSS descendant selector or CSS child element selector is used most often. It is used if it is necessary to select elements of a certain type from many child elements. For example, you need to select all the links that are in the li element. In this case, use this selector. When using chains of such selectors, always ask yourself whether an even shorter sequence of selectors could be used to highlight a given element.
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
6) X + Y
div + p ( font-family: "Helvetica Neue", Arial, sans-serif; font-size: 18px; )Adjacent element selector chooses only an element of type Y that comes immediately after the X element. In this case, each paragraph immediately after each div element will receive a special font type and size.
- Which browsers are supported:
- IE7+
- Firefox
- Chrome
- Safari
- Chrome
7) X > Y
#content > ul ( border: 1px solid green; )CSS descendant selector. The difference between the X Y and X > Y selectors is that the CSS selector in question will only select immediate children of elements (it will only select direct descendants). Eg:
- List item
- Descendant of the first element of the list
- List item
- List item
The CSS selector #content > ul will only select a ul that is a direct child of the div with id="container" . It will not select a ul that is a child of the first li. This is a fairly speedy CSS selector.
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
8) X ~ Y
ol ~ p ( margin-left: 10px; )Selector of sister (subling) elements less strict than X + Y. It will select not only the first one, but also all other p elements following ol.
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
Pseudo-class:link used to select all links that have not yet been clicked. If you need to apply a certain style to already visited links, then use pseudo-class:visited.
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
10)X
a(color:red;)CSS attribute selector. This example selects only those links that have a title attribute.
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
11) X
a ( color: yellow; )- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
12) X
a ( color: #dfc11f; )The asterisk means that the value you are looking for must be somewhere in the attribute (any part of the href attribute). This way, links from https://www..stijit.. will also be selected. The gold color will be applied to all selected links.
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
13) X
a ( background: url(path/to/external/icon.png) no-repeat; padding-left: 15px; )Some sites have small arrow icons next to links to other sites to indicate that they are external links. The karat “^” is a symbol to indicate the beginning of a line. Thus, to select all tags whose href begins with http, you need to use a CSS selector with karat, as shown in the example above.
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
14)X
a(color:green;)This uses a regular expression and the $ symbol to indicate the end of the line. In this example, we are looking for all links that refer to images with a .jpg extension.
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
15) X
a(color:green;)Here we apply CSS custom attribute selector. We add our own data-filetype attribute to each link:
link
Now, using the above CSS selector, you can select all links leading to images with any extension.
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
16)X
The tilde (~) allows you to highlight a specific attribute from a list of attributes separated by a space. You can write our own data-info attribute, in which you can specify several keywords through a space. This way you can indicate that the link is external and leads to the image.
link
Using this technique, we can select elements with the combinations of attributes we need:
/* Select an element whose data-info attribute contains the value external */ a ( color: green; ) /* Select an element whose data-info attribute contains the value image */ a ( border: 2px dashed black; )
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
17) X:checked
input:checked ( border: 3px outset black; )This pseudo-class only highlights elements such as a checkbox or radio button, and only when they are already in the checked state.
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
18) X:after
The :before and :after pseudo-classes are very useful - they create content before and after the selected element.
Clearfix:after ( content: ""; display: block; clear: both; visibility: hidden; font-size: 0; height: 0; ) .clearfix ( *display: inline-block; _height: 1%; )
Here, using the pseudo-class:after, an empty line is created after the block with the class.clearfix, and then cleared. This approach is used if it is not possible to apply the overflow: hidden property.
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
19) X:hover
div:hover ( background-color: rgba(11,77,130,0.5); )Applies a specific style to an element when the mouse cursor hovers over it. Old versions Internet Explorer apply:hover only to links.
A:hover ( border-bottom: 1px dotted blue; )
- Which browsers are supported:
- IE6+ (Only applies to links in IE6)
- Chrome
- Firefox
- Safari
- Opera
20) X:not(selector)
div:not(#content) ( color: grey; )Pseudo-class not (negations) This is useful when, for example, you need to select all divs except the one with id="content" .
Using the same principle, you can select all elements except p:
*:not(p) ( color: blue; )
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
21) X::pseudoElement
p::first-line ( font-weight: bold; font-size: 24px; )Pseudo-elements can be used to apply styles to portions of elements—for example, the first line of a paragraph or the first letter of a word. Applies only to block elements.
Selecting the first letter of a paragraph:
P::first-letter ( font-family: cursive; font-size: 30px; font-weight: bold; padding-right: 1px; )
Selecting the first line in a paragraph:
P:first-line ( font-size: 28px; font-weight: bold; )
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera
22) X:first-child
ul li:first-child ( border-top: none; )Pseudo-class first-child selects only the first child of the parent element. Often used to remove a border from the first element of a list. This pseudo-class has been around since CSS 1.
- Which browsers are supported:
- Chrome
- Firefox
- Safari
- Opera 3.5+
- Android
23) X:last-child
ul > li:last-child ( border-bottom: none; )Pseudo-class last-child selects the last child of the parent element. He only appeared since CSS 3.
- Which browsers are supported:
- IE9+ (IE8 supports first-child, but not last-child. Microsoft (c))
- Chrome
- Firefox
- Safari
- Opera 9.6+
- Android
24) X:only-child
div p:only-child ( color: green; )Pseudo-class only-child allows you to select those elements that are the only children of their parents.
- Which browsers are supported:
- Chrome
- Firefox
- Safari 3.0+
- Opera 9.6+
- Android
25) X:nth-child(n)
li:nth-child(3) ( color: black; )Selects child element by the number specified in the parameter. nth-child selector takes an integer as a parameter, but counts from 1, i.e. if you need to select the second list item, use li:nth-child(2) . All pseudo-classes using nth-child appeared only starting with CSS 3.
- Which browsers are supported:
- Chrome
- Firefox 3.6+
- Safari 3.1+
- Opera 9.6+
- Android 2.1+
- iOS 2.0+
26) X:nth-last-child(n)
li:nth-last-child(2) ( color: red; )If you have a large list of elements in ul and you need to select the third element from the end? Instead of writing li:nth-child(109) you can use last child selector nth-last-child. This method is the same as the previous one, but counting from the end.
- Which browsers are supported:
- Chrome
- Firefox 3.6+
- Safari 3.1+
- Opera 9.6+
- Android 2.1+
- iOS 2.0+
27) X:nth-of-type(n)
ul:nth-of-type(3) ( border: 1px dotted black; )If there are four unordered lists on a page and you only need to style the third one, which does not have a unique id, you should use nth-of-type.
- Which browsers are supported:
- Chrome
- Firefox 3.6+
- Safari 3.1+
- Opera 9.6+
- Android 2.1+
- iOS 2.0+
28) X:nth-last-of-type(n)
ul:nth-last-of-type(3) ( border: 2px ridge blue; }Pseudo-class nth-last-of-type(n) is intended to select the nth element of a certain type from the end.
- Which browsers are supported:
- Chrome
- Firefox 3.6+
- Safari 3.1+
- Opera 9.6+
- Android 2.1+
- iOS 2.0+
29) X:only-of-type
li:only-of-type ( font-weight: bold; )Pseudo-class only-of-type selects elements that have no neighbors within the parent element. For example, you can select all uls that contain only lonely lis.
- Which browsers are supported:
- Chrome
- Firefox 3.5+
- Safari 3.1+
- Opera 9.6+
- Android 2.1+
- iOS 2.0+
30) X:first-of-type
ul:first-of-type > li:nth-child(3) ( font-style: italic; )First-of-type pseudo-class selects the first element of the given type.
- Which browsers are supported:
- Chrome
- Firefox 3.5+
- Safari 3.1+
- Opera 9.5+
- Android 2.1+
- iOS 2.0+
2024 gtavrl.ru.