Computer literacy, assistance and repair

Css adjacent elements. CSS Child and Neighbor Selectors

Vlad Merzhevich

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

Lorem ipsum dolor sit amet.

In this example the tag is a child of the tag

Because it is inside this container. Respectively

Acts as a parent .

Lorem ipsum dolor sit amet.

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

Doesn't affect their attitude at all.

Lorem ipsum dolor sit amet, consectetuer adipiscing elite.

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

To control the style of adjacent elements, use the plus symbol (+) between two selectors. The general syntax is as follows.

Selector 1 + Selector 2 (Description of style rules)

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

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

Example 11.1. Using adjacent selectors

HTML5 CSS 2.1 IE Cr Op Sa Fx

Adjacent selectors

Lorem ipsum dolor sit amet, consectetuer adipiscing elite.

Lorem ipsum dolor sit amet, consectetuer adipiscing elite.

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

Rice. 11.1. Highlighting text with color using adjacent selectors

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

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

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

Example 11.2. Change paragraph style

HTML5 CSS 2.1 IE Cr Op Sa Fx

Change paragraph style

Methods for catching a lion in the desert

Sequential search method

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

Important Note

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

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

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

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

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

, which has a class named sic added.

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

And

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

And

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

Example 11.3. Spaces between headings and text

HTML5 CSS 2.1 IE Cr Op Sa Fx

Adjacent selectors

Heading 1

Heading 2

Paragraph!

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

Questions to check

1. Which tags in this code are adjacent?

Sulfuric acid formula:H 2 SO 4

  1. AND

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

2. The following HTML code is available:

Fermat's Last Theorem


X n+Y n
= Z n


where n is an integer > 2

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

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

In previous subchapters, we studied the relationships between tags in an HTML document, including looking at child element selectors. Now it's time to get acquainted with sibling selectors and adjacent selectors.

Adjacent selectors

Adjacent selectors (also called adjacent selectors) select web page elements that have a common parent and are adjacent to each other. The style is applied to the last element specified in the selector.

Example: Let's say you need each paragraph

Which comes first after the title

, had an italic font. This can be achieved using CSS code like this:

H1+p ( font-style: italic; )

When writing this rule, you first need to specify the name of the first neighbor, then add the + symbol and the name of the second neighbor (the one to which we want to apply the style). You can create longer combinations. The selector writing scheme is as follows: selector1+selector2+…+selectorN () (the style is applied to selectorN).

Writing examples:

/* Indent from paragraph to image 30px */ p+img ( padding-top: 30px; ) /* Green color for the paragraph that follows h3 in conjunction with h2 */ h2+h3+p ( color: green; )

Related selectors

Related selectors (other names: sister, sibling) allow you to select elements of an HTML page that are related to each other (that is, having a common parent and being on the same level). Sister selectors are similar to their sibling selectors, but differ in that the style is applied to all elements of the selected type, not just the first one. The tilde character ~ is used instead of the + sign.

Example: let's change the previous problem a little and imagine that you need to make italic font for all paragraphs

Which come after the title

. The CSS code will look like this:

H1 ~ p (font-style: italic; )

...and some HTML for example:

Heading 1

Heading 2

Take a look at the HTML code: the style will be applied to all tags

Which follow after tag

and are before parent closing tag
. In our version there are 3 elements

To which the style will be applied. Please note that the tag

This won't hurt in any way. Note also that in this case the style will not applied to that tag

Which is located above

, as well as to the tag

Having another parent

.

conclusions

Using adjacent selectors, you can style an element when it immediately follows another element (or group of elements). This works with elements that are at the same level and have a common parent.

With sibling selectors, you can apply a style to all elements of the selected type when they immediately follow another element (or group of elements). This works with elements that are at the same level and have a common parent.

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. It's fat 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 window

Result:

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

3. One of several attribute values

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

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

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

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

Our phone: 777-77-77


Our address: Moscow st. Sovetskaya 5

You will get the following result:

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

4. Hyphen in attribute value

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

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

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

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



  • Point 2



Result:

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

5. The attribute value starts with specific text

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

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

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

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

Result:

The example shows how to display external links and internal links 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.

An adjacent element selector selects an element that is located directly behind another element in the document code given element. Let's take a piece of html code as an example.

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

There are three tags:

, And . Tags And nested in a container

They are children of him. But in relation to each other they are neighboring.

The syntax of an adjacent selector is: the selector of the previous element, followed by a "+" sign, followed by the selector of the element being selected. Let's work the adjacent selector:

Adjacent selector in CSS.

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

Here fatty And emphasized elements, more inclined.

In the example you can see that the adjacent element selector was triggered in the first paragraph. Here are the tags And go one after another. And in the second paragraph, the tag is used between them , now there are two other adjacent pairs of tags: + And + .

Error in in this case will count the tag adjacent to the tag

Tag here is a child of the tag

And he, in turn, is a parent .

The example below will not work:

Adjacent selector in CSS.

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

Here fatty And emphasized elements, more inclined.

More real example

Let's look at how the adjacent selector works using a more realistic example. In large articles containing several sections marked with tags

, it is advisable to increase the top margin (margin-top property). An indentation of 30px will make the text readable. But if the tag

comes right after

, and this could be at the beginning of the article, the top indent above the tag

will be redundant. This problem can be solved using an adjacent element selector.

Here is the html code with an example of how the adjacent element selector works.

Adjacent selector in CSS

Hello!

Heading h2

Heading h2

The text of the paragraph is about incredible adventures.

Heading h2

The text of the paragraph is about incredible adventures.

Heading h2

The text of the paragraph is about incredible adventures.

Also, using the adjacent selector tool, it is convenient to adjust the indent between the heading and the first paragraph of the section, in our example these are tags

And

It is also worth noting that to reduce indentation it is convenient to use negative values.

Adjacent selector in CSS

Hello!

Heading h2

The text of the paragraph is about incredible adventures.

Heading h2

The text of the paragraph is about incredible adventures.

Heading h2

The text of the paragraph is about incredible adventures.

Heading h2

The text of the paragraph is about incredible adventures.

Now an example of how to use an adjacent selector to select all elements of the list except the first one.

Adjacent selector in CSS

  • List item #1.
  • List item #2.
  • List item #3.
  • List item #4.

This is what will happen as a result of this example:

Figure 1. Work of example No. 5.

1 Jun 2015

In contrast, neighboring ones are used less often. The main difference is that they must follow the other. To make it easier for you to understand this topic, I suggest you look at this structure:

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

As you probably guessed from the previous lesson, tags 2, 3, 4, 5, 6 are context selectors for tag1. In turn, neighboring selectors will be: tag2 and tag3, tag4 and tag5, But at the same time tag2 And tag4 are not adjacent. The style properties will be applied to the last element that you specify as adjacent. You just have to follow the order of the selectors. The general writing syntax is:

Selector1 + selector2+ ...+selectorN ( property1: value; property2: value; ... propertyN: value)

Let's look at this example:

Adjacent selectors

Heading

Tag p is an adjacent selector to the tag h1

This text should be green

Related publications