CSS child combinator
Created By: chatGPT
CSS Child Combinator is used to select elements that are direct children of a specified element. It is denoted by the
>
symbol. This combinator allows for more specific styling, targeting elements immediately under a parent without affecting deeper nested elements. It's particularly useful for styling layouts or hierarchies where direct child relationships are crucial./* Example of using child combinator */
.parent > .child {
background-color: lightblue;
padding: 10px;
}
/* HTML Structure */
<div class="parent">
<div class="child">I am a direct child!</div>
<div>
<div class="child">I am NOT a direct child!</div>
</div>
</div>
In this example, the first
.child
element will receive the specified background color and padding, while the nested .child
element within the second <div>
will not, since it's not a direct child of the .parent
element./* Style for a direct child under the parent class */
.parent > .child {
color: red;
}
/* Style for deeper nested children */
.parent .child {
color: blue;
}
When you want to apply styles based on a specific hierarchy in your HTML structure, using the child combinator provides clarity and maintains the integrity of the design. Remember to use it wisely to control the scope of your styles effectively.
<!-- Example HTML -->
<div class="container">
<div class="parent">
<div class="child">Direct Child</div>
<div>
<div class="child">Nested Child</div>
</div>
</div>
</div>