CSS selects the first layer of child elements
CSS Select First-Level Child Elements
In CSS, we often need to select child elements at a specific level for styling. Sometimes we want to select only first-level child elements, ignoring descendant elements. In this case, we can use CSS selectors to precisely target first-level child elements.
The Difference Between Child and Descendant Elements
In HTML documents, elements have a distinct parent-child relationship. Child elements are directly contained within a parent element, while descendant elements are contained within a parent element but are not direct children of the parent element. Here is a simple HTML structure example:
<div class="parent">
<div class="child1">Child Element 1</div>
<div class="child2">
<div class="grandchild">Grandchild Element</div>
</div>
</div>
In this example, .child1
and .child2
are children of .parent
, and .grandchild
is a descendant of .parent
, but not a direct child.
Selecting First-Level Children with CSS
To select the first-level children of an element, we can use the >
notation. This notation is called a child selector, and it’s a convenient way to select first-level children.
Here’s a simple example showing how to use the child selector to select first-level child elements:
<style>
.parent > .child {
color: red;
}
</style>
<div class="parent">
<div class="child">Child Element 1</div>
<div class="child">Child Element 2</div>
</div>
In this example, the .parent > .child
selector selects all .child
elements that are direct children of the .parent
element and sets their text color to red.
Sample Code and Results
Let’s demonstrate a more specific example, showing how to use CSS to select and style first-level child elements:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS selection example of first-level sub-elements</title>
<style>
.parent > .child {
background-color: lightblue;
padding: 10px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">Child Element 1</div>
<div class="child">Child Element 2</div>
<div class="not-child">
<div class="grandchild">Grandchild Element</div>
</div> </div>
</body>
</html>
In this example, we apply a light blue background color, 10px padding, and a 10px bottom margin to all .child
elements under the .parent
element. Meanwhile, the .not-child
and .grandchild
elements are unaffected because they are not direct children of .parent
.
Summary
By using the child selector >
, we can easily select the first-level children of an element and add styles to them. This technique is very useful when designing page layout and styling, allowing us to more precisely control the appearance and layout of page elements.