Hardware and software setup

CSS: child selectors. DOM Techniques: Parent, Child, and Neighbor Elements Which element is the parent of the title tag

Hello dear readers! Continuing the theme of CSS selectors, I want to bring to your attention description of child and context selectors, as well as their comparative analysis, since they are very similar in application logic, although they have some differences.

In my publications, I dwelled in some detail on various types CSS selectors: ; as well as . By the way, in the last article, where they understood different types attribute selector, I described in some detail how my theoretical calculations can be immediately checked by making changes to the HTML and CSS code online using the built-in tool Google Chrome(). These editing tools have the latest modifications of all popular browsers, including the Firebug plugin for Firefox ().

You can also study the theoretical material of this post by editing any page of any site! To do this, simply press F12 if you are using Google Chrome or Mozilla Firefox(). And now I will present the content of the p tag, on the example of which we will study child and context CSS selectors:

This paragraph includes em and strong formatting tags, which highlight text bold And in italics.

Using the editing tool described above, I inserted this paragraph directly into this article by typing the appropriate text on the left side of the editing window, as a result of which the text of this paragraph appeared at the very top of the page:


This HTML construct , . This paragraph will be experimental in today's publication, using its example I will show how the design of its text changes, depending on which selectors - child or context - are used in the CSS rule.

A child is an element that is located directly inside the parent element.. Before proceeding directly to the topic, I will give a picture that reflects the hierarchy of tags in HTML document on the example of the paragraph, the text of which is given above and which we will analyze today:

This design is also called a tree of elements. This figure clearly shows the nesting of containers, which implies a hierarchical relationship between tags. The p paragraph tag is a child of the relation . At the same time, the strong tag is not a child of the div, since it is located in the p container.

Child CSS selector

The child selector in the element tree is always located directly inside the parent element, in this case the syntax for writing a CSS selector is as follows:

The style will be applied to Selector 2, but only if it is a child of Selector 1. Let's take a closer look using the screenshot above with the element tree. For example, following the syntax, you can set the following rule:

P> em (color: green;)

This rule will affect the last word of the paragraph as "Italic" because that is what is enclosed between the opening and closing em tags. The em tag is a child of p because it is placed directly inside it, so the content text, namely the word “italics”, will be colored green.


However, the other em tag is not a direct child of the p tag, because it is part of the strong tag, so the “em and strong formatting tags” portion of the paragraph will not be colored.

Contextual CSS selector

It's time to figure it out what is context CSS selector . When laying out a particular page of the site, tags are very often nested one inside the other. In order for the styles for such elements to work correctly, selectors are used that act in some context, hence the name.

If in order for the CSS rule to be applied, the child selector must necessarily be located directly inside the parent element (first nesting level), then for the context selector this is completely unimportant and any nesting level can be applied, anyway, the element properties will be transferred from the parent. The syntax is thus:

As you can see, the context selector consists of simple selectors separated by a space. For contextual selectors, it is allowed to use two or more nested tags. Let's now compose the CSS rule for the paragraph under test, which I cited above:

P'em (color: green;)


As you can see, not only the text of the part of the content of the paragraph, which is directly enclosed in the em formatting tag, that is, the word “italic”, is colored green, but also the text section of another em tag, which is also part of the strong tag. This happened because the rule with the context selector is in effect, for which the nesting level is not important, unlike the child selector. This is the fundamental difference between the child and context selectors.

Let's look at another example of the interaction of context and child selectors with our paragraph. Let's write the following CSS rules for the child and context selectors:

Div em (color: red;) p > em (color: green;)

After that, our paragraph takes on the following format:


As you can see, the piece of text enclosed in the em and strong tags is colored red because the contextual selector rule is true for it, that is, the em tag is enclosed in the strong and div containers, and the nesting level, as already noted, does not matter .

The question arises: why is the word “italic”, which is also the content of em, colored green? After all, the context selector rule is also relevant for him. But the child selector rule also applies to this portion of the text of the paragraph, because it does not contradict the condition that for the child selector, the element must be directly within the p tag.

The fact is that CSS has a law of precedence for CSS properties below. That is, in this case, the child selector rule is lower in the document than the CSS styles written for the container div's contextual selector. Therefore, the word “italics” is green. If you swap them, then the “p> em (color: green;)” rule ceases to work and the “italic” section of the text will be red.

CSS child selectors are selectors that are used to apply styles to elements only when they are children of other (parent) elements. Like child selectors, child selectors are compound selectors made up of simple selectors (classes, ids, etc.).

And again, if you forgot what child elements are, then let's remember by examining an example you already know.

<тег1> <тег2>... <тег3><тег4>...

An element is said to be a child of another element if it is inside it at the first nesting level. In our example<тег2>And<тег3>are daughters<тег1>, but<тег4>- this is the daughter<тег3> .

Child selectors consist of two or more simple selectors separated by ">", where the parent is listed first, then its child, then the child of that child, and so on. That is, as in the descendant selectors, the path through the document tree is specified. Styles will only be applied to elements whose selectors are last in the list. General syntax:

selector1 > selector2 (

Spaces on both sides of the ">" sign may or may not be included, as desired.

An example of using CSS child selectors

Child selectors

Paragraph 1.

Paragraph 2.

Result in browser

Paragraph 1.

Paragraph 2.

In this example, you need to pay attention to two points. There are three elements here, but only two of them have borders, padding, and margins. Why? And the second moment. Only the first paragraph has blue text.

Internet Explorer 6.0 doesn't understand child selectors, so if you're designing your site with this old browser in mind, keep that in mind.

Child selectors in HTML tables

Many beginners (and sometimes not beginners) in site creation face certain problems when using child selectors in HTML tables. To give you an idea of ​​what we are talking about, let's look at such an ordinary table.

Cell 1.1Cell 1.2
Cell 2.1Cell 2.2

And now the question. What would you do if you needed to use child selectors to go from the tag to the cells? If you decide to write like this, then it is wrong:

table > tr > td( property: value; property: value; ... )

Can you guess why it's wrong? Not? The fact is that you forgot about one more element - which, even if not explicitly specified, is still invisibly present in every HTML table. It just doesn't have the required opening and closing tags, so it's often overlooked. By the way, yes, HTML Tutorial we did not go through it, since in reality its explicit indication is rarely needed. Well, I think you have already guessed what the correct entry will be, but I will show you anyway.

table > tbody > tr > td( property: value; property: value; ... )

By the way, not only tables have elements with optional opening tags, there are also such elements. It’s just that in practice, “forgetfulness problems” occur most often with tables, which is why I focused your attention on this.

Homework.

  1. Set the font on the page to Arial with a size of 0.9em and some background.
  2. Write several headings and paragraphs on the page, change the size and color of the heading text as you see fit.
  3. Make the links directly in the paragraphs of the page blue without underlining. But at the same time, if links are additionally framed with any tag, for example, for italics, then they should be displayed already with an underline and red color. Once again I draw your attention to the fact that it is not necessary to prescribe link styles with each framing tag separately, do it universally. How? Think.
  4. Create a small menu on the right side of the page and fix it, for this you need a property and a couple of properties that accompany it, you will figure it out there. At the same time, let the menu not only remain in place within the browser window, but also, when scrolling, does not crawl onto the page content.

Think last paragraph lesson will be the most difficult for you, but do not try to immediately completely immerse yourself in the development of positioning. Just do your homework. By the way, this item will not work in Internet Explorer 6.0, as the old man does not understand fixed positioning.

Vlad Merzhevich

A child element is an element that is directly inside the parent element. To better understand the relationships between document elements, let's break down a little code (Example 12.1).

Example 12.1. Nesting elements in a document

HTML5 CSS 2.1 IE Cr Op Sa Fx

Lorem ipsum

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat.

Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

IN this example several containers are used, which are located one inside the other in the code. This can be seen more clearly in the element tree, this is the name of the structure of relations between document tags (Fig. 12.1).

Rice. 12.1. Tree of elements for an example

On fig. 12.1 in a convenient form nesting of elements and their hierarchy is presented. Here as a child of the tag

favored tag

However, the tag is not a child of a tag

, because it is located in a container

Let's get back to selectors. A child selector is one that is located directly inside the parent element in the element tree. The syntax for using such selectors is as follows.

Selector 1 > Selector 2 ( Description of style rules )

The style is applied to Selector 2, but only if it is a child of Selector 1.

Referring again to Example 12-1, the P > EM ( color: red ) style would be set for the first paragraph of the document, because the tag is inside the container

And will not give any result for the second paragraph. And all because the tag in the second paragraph is located in the container , so the nesting condition is violated.

In their logic, child selectors are similar to context selectors. The difference between them is the following. A child selector is only styled when it is a direct child, in other words, directly within the parent element. For a context selector, any level of nesting is allowed. To make it clear what is at stake, let's analyze the following code (example 12.2).

Example 12.2. Contextual and child selectors

HTML5 CSS 2.1 IE Cr Op Sa Fx

Child selectors

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat.

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

Rice. 12.2. Text color set with child selector

Per tag in the example, two rules work simultaneously: context selector (tag located inside

) and child selector (tag is a child of

). At the same time, the rules are equivalent, since all the conditions for them are met and do not contradict each other. In such cases, the style is applied, which is located in the code below, so the italic text is displayed in red. As soon as the rules are reversed and put DIV I below, the text color will change from red to green.

Note that in most cases, adding child selectors can be omitted by replacing them with context selectors. However, the use of child selectors gives you more control over element styles, which ultimately allows you to get the desired result, as well as simple and descriptive code.

It is most convenient to use these selectors for elements that have hierarchical structure- this includes, for example, tables and various lists. Example 12-3 shows how to change the look of a list using styles. By nesting one list into another, we get a kind of menu. The headings are laid out horizontally, while the set of links is placed vertically below the headings (Figure 12.3).

Rice. 12.3. Menu List

To position text horizontally, the float style property is added to the LI selector. In order to separate the style of the horizontal and vertical lists, child selectors are used (example 12.3).

Example 12.3. Using child selectors

HTML5 CSS 2.1 IE Cr Op Sa Fx

Child selectors

In this example, the child selectors are required to separate the style of the top-level list items and nested lists that perform different tasks, so the style for them should not overlap.

Questions to check

1. What color will bold italic text be in code

Illumination standards are based on basis of classification of visual works on certain quantitative grounds.

When using the following style?

P (color: green; )
B (color: blue; )
I (color: orange; )
B > I ( color: olive; )
P > I (color: yellow; )

  1. Green.
  2. Blue.
  3. Orange.
  4. Olive.
  5. Yellow.

2. Which element is the parent of the tag ? </b></p> <ol><li><HEAD></li> <li><BODY></li> <li><HTML></li> <li><META></li> <li><!DOCTYPE></li> </ol><p><b>3. For which tag the element<!DOCTYPE>acting as a parent?</b></p> <ol><li><HTML></li> <li><TITLE></li> <li><BODY></li> <li><HEAD></li> <li>Not for one tag.</li> </ol><h2>Answers</h2> <p>1. Olive.</p> <p>3. Not for one tag.</p> <p>Child elements are elements that are located directly inside the parent element. Pay attention to the words: directly inside.</p> <p>Let's look at a simple html code example:</p><p> <!DOCTYPE html> <html> <head> <title>child elements.

paragraph and in it fatty element, and here inclined element.

Here fatty And underlined and oblique elements.

There are two paragraphs in this code. Paragraphs contain inline elements , And . In the second paragraph, the tag nested in a tag .

Now let's add CSS styles to this html code using child selectors.

Syntax of child selectors:

Selector 1 > Selector 2 ( Property: value; )

Here is the updated code:

child elements.

paragraph and in it fatty element, and here inclined element.

Here fatty And underlined and oblique elements.

So, remember: a child element is an element nested directly in the parent. That is, a child element is a descendant of the first level. Let's take a look at the tag. , in the first paragraph it is nested in the tag

And in the second it is nested in the tag , although it is also a child of the tag

Therefore, in the second paragraph of CSS, the rule for the child selector p>i ( color : blue ; ) will not work - the italic text of the second paragraph will not be displayed in blue.

Figure 1. Work example #1.

Get to the html element the second paragraph can be done using the CSS rule: p>u>i ( color : blue ; ).

Let's use this rule to set the italic text of the second paragraph to yellow.

child elements.

paragraph and in it fatty element, and here inclined element.

Here fatty And underlined and oblique elements.

This style will work and italic text in the second paragraph will be displayed in yellow.

Figure 2. Work example #2.

More complex example

We have html code:

child elements.

By default it is interpreted like this:

Task: when CSS help turn this list into a horizontal menu.


Figure 3. Purpose of transformations.

Here is a solution to this problem using child selectors:

child elements.

For a better understanding of this example, read on.

You have reached the third part of this chapter. Here you will learn how to use child selectors in CSS, as well as some additional pseudo-classes for more precise selection.

CSS Child Selectors

In a previous article, we talked about family ties between elements of an HTML document, including child elements. Let's look at an example of how these links can be used in CSS.

Imagine that you need to style only those tags

which are children of without affecting the rest

(for example,

Subsidiaries of

).
How to do it? Very simple: create a child selector:

Body > p ( color: #333; )

Note the > symbol after body . With it, you indicate that the style is applied exclusively to child tags.

parent . If the symbol is removed, then the style will be applied to absolutely all tags.

which are inside the tag , although they may not be children of it.

Additional pseudo-classes

CSS3 has a number of pseudo-classes for dealing with child elements. Below is a description of each of them, examples of usage, and differences between pseudo-classes of the form "child" and "of-type".

  • :first-child - with this pseudo-class, you can apply a style to the specified element of the web page, provided that it is first
  • :last-child - the style is applied to the specified element of the web page, provided that it is last a child of its parent;
  • :nth-child - allows you to select even (even) and odd (odd) child elements; also using this pseudo-class, you can style alternating child elements using expressions like an + b and numbers;
  • :only-child - applies to the child element, provided that it is the only a child of a parent;
  • :first-of-type - the style is applied to the first element of the specified type(even if this element is not the first child of its parent and there are other child elements of other types above it);
  • :last-of-type - works exactly like the previous pseudo-class, with the only difference that the style is applied to the last element of the specified type;
  • :nth-of-type - similar in principle to :nth-child , but focuses on type element;
  • :only-of-type - applied to a child element of the specified type, provided that it is in the parent the only child of his type.

Usage example for :first-child, :last-child and :nth-child

First child

Second child

third child

odd number
Even number
odd number
Even number

Last child

/* CSS */ p:first-child ( font-weight: bold; text-transform: uppercase; ) p:last-child ( font-style: italic; font-size: 0.8em; ) p:nth-child( 3) ( color: red; ) tr:nth-child(odd) ( background-color: #A2DED0; ) tr:nth-child(even) ( background-color: #C8F7C5; ) Screenshot: application:first-child, :last-child and :nth-child

We have written a CSS style for the child elements of a simple HTML document, where the tag

is a parent for tags

,

. Let's take the CSS one by one.

The first rule, p:first-child, concerns the p element: if it is the first child of its parent, then a style is applied to it (in our case, this is bold font and converting text to uppercase). If in the given HTML code immediately after the opening tag

add another tag (for example,

), then the p:first-child style will no longer be displayed, because

Will no longer be the first child tag. In this case, the first child will be h2 .

The same thing happens with the p:last-child rule - the CSS style will be applied to the tag

Only when he appears the last child of its parent. Add after

Any other tag of a different type and you will see the p:last-child rule no longer apply.

The p:nth-child(3) rule works for third child tag

(this is indicated by the number 3 in brackets). The font color for this paragraph becomes red. You can change the number 3 (for example, to 2) and see the result.

The tr:nth-child(odd) and tr:nth-child(even) rules work for odd and even tr elements, respectively. You can see the result in the screenshot, as well as copy all the code and experiment with the styles yourself.

Usage example: first-of-type, :last-of-type, :nth-of-type and :only-of-type

First child

Second child

third child

fourth child

Fifth child

Last child

/* CSS */ p:first-of-type ( color: violet; text-transform: uppercase; ) p:last-of-type ( font-style: italic; font-size: 0.8em; ) p:nth- of-type(3) ( color: red; ) p:nth-of-type(odd) ( background-color: #A2DED0; ) p:nth-of-type(even) ( background-color: #C8F7C5; ) h3:only-of-type ( text-decoration: underline; )
Screenshot: applying :first-of-type, :last-of-type, :nth-of-type and :only-of-type

The first CSS rule you see is p:first-of-type . What does it do? It selects a child element of type p that first meets the parent. And it doesn't matter where this tag is located among elements of other types - on the first, second or tenth. This is the difference between the :first-child and :first-of-type pseudo-classes.

The second rule, p:last-of-type, applies the style to last child element of type p . As you can see from the HTML code, after the last tag

There is also a tag

, the presence of which does not affect the execution of the CSS rule in any way (unlike the :last-of-child option).

The next rule, p:nth-of-type(3), changes the font color to red. Apply this style to the tag

Which is third by an element of its type in the parent. In the screenshot you can see that the red color is applied to the tag

Which in fact is the fifth child of the tag

. But if you do not take into account elements of other types, then it turns out that the tag

With a red font, it is in third place (among the tags of its type). This is how this rule works.

The rules p:nth-of-type(even) and p:nth-of-type(odd) work similarly: since the name p is given before the colon, the even and odd child elements of type p are selected and colored with the given colors. The rest of the elements are skipped.

The last rule - h3:only-of-type - applies to the content of the tag

, making the text underlined. This style only works because the tag

is an the only child element of its type. If you add another tag to the HTML code

, the style will not be applied.

conclusions

The CSS child selector allows you to change the style of a child element in an HTML document based on who its parent is.

With the help of additional pseudo-classes: first-child, :last-child, :nth-child, :only-child, you can style the child elements of an HTML document, focusing on their location, numbering in the element tree.

Pseudo-classes :first-of-type, :last-of-type, :nth-of-type, :only-of-type allow you to style child elements of an HTML document based on their type, as well as numbering in the element tree .

Liked the article? Share with friends!
Was this article helpful?
Yes
Not
Thanks for your feedback!
Something went wrong and your vote was not counted.
Thanks. Your message has been sent
Did you find an error in the text?
Select it, click Ctrl+Enter and we'll fix it!