Комбинации селекторов

В процессе перевода.

The final selectors we will look at are called combinators, because they combine other selectors in a way that gives them a useful relationship to each other and the location of content in the document.

Prerequisites: Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of how CSS works (study CSS first steps.)
Objective: To learn about the different combinator selectors that can be used in CSS.

Селектор потомков

You have already come across descendant selectors in previous lessons — selectors with spaces in between them:

body article p

These selectors select elements that are descendants of others selector. They do not need to be direct children to match.

In the example below we are matching only the <p> element which is inside an element with a class of .box.


Дочерний комбинатор - это символ "больше, чем" (>). Совпадение будет выявлено, только если элементы, соответсвующие селектору справа от символа, являются прямыми потомками элементов селектора слева. Все элементы на более низких уровнях иерархии не будут рассматриваться. Например, чтобы выбрать только те элементы <p>, которые являются дочерними элементами <article>, селетор пишется так:

article > p

Другой пример. Имеется неупорядоченный список, заключающий в себе другой, упорядоченный список. Дочерний комбинатор используется для того, чтобы выбрать только те элементы <li>, которые являются прямыми потомками <ul>, и присвоить им верхнюю границу красного цвета.

Если вы уберёте символ >, указывающий на то, что это селектор с дочерним комбинатором, селетор превратится в селектор всех потомков (комбинатор - пробел) и все элементы <li> получат верхнюю границу красного цвета.

Смежные селекторы

The adjacent sibling selector (+) is used to select something if it is right next to another element at the same level of the hierarchy. For example, to select all <img> elements that come right after <p> elements:

p + img

A common use case is to do something with a paragraph that follows a heading, as in my example below. Here we are looking for a paragraph which is directly adjacent to an <h1>, and styling it.

If you insert some other element such as a <h2> in between the <h1> and the <p>, you will find that the paragraph is no longer matched by the selector and so does not get the background and foreground color applied when the element is adjacent.

Братские элементы

If you want to select siblings of an element even if they are not directly adjacent, then you can use the general sibling combinator (~). To select all <img> elements that come anywhere after <p> elements, we'd do this:

p ~ img

In the example below we are selecting all <p> elements that come after the <h1>, and even though there is a <div> in the document as well, the <p> that comes after it is selected.

Использование комбинаторов

You can combine any of the selectors that we discovered in previous lessons with combinators in order to pick out part of your document. For example if we want to select list items with a class of "a", which are direct children of a <ul>, I could use the following.

ul > li[class="a"]  {  }

Take care however when creating big lists of selectors that select very specific parts of your document. It will be hard to reuse the CSS rules as you have made the selector very specific to the location of that element in the markup.

It is often better to create a simple class and apply that to the element in question. That said, your knowledge of combinators will come in very useful if you need to get to something in your document and are unable to access the HTML, perhaps due to it being generated by a CMS.

Moving on

This is the last section in our lessons on selectors. Next we will move on to another important part of CSS — the CSS Box Model.

In this module

  1. Cascade and inheritance
  2. CSS selectors
  3. The box model
  4. Backgrounds and borders
  5. Handling different text directions
  6. Overflowing content
  7. Values and units
  8. Sizing items in CSS
  9. Images, media, and form elements
  10. Styling tables
  11. Debugging CSS
  12. Organizing your CSS