Descendant vs direct child
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Selector Example: Descendants vs Direct Children</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
color: #333;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
/* Descendant selector */
.container p {
background-color: #f0f0f0;
padding: 10px;
border-radius: 5px;
transition: background-color 0.3s ease;
}
/* Direct child selector */
.container > p {
border-left: 5px solid #4CAF50;
}
/* Descendant selector with pseudo-class */
.container p:hover {
background-color: #e0e0e0;
}
/* Direct child selector with nth-child */
.container > p:nth-child(odd) {
background-color: #FFF9C4;
}
/* Nested structure styles */
.nested {
border: 2px dashed #2196F3;
padding: 10px;
margin: 10px 0;
}
/* CSS3 feature: Flexible Box Layout */
.flex-container {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.flex-container > div {
flex-basis: calc(50% - 10px);
margin-bottom: 10px;
}
/* CSS3 feature: Custom properties (variables) */
:root {
--highlight-color: #FF5722;
}
/* Using the custom property */
.highlight {
color: var(--highlight-color);
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<p>This is a direct child paragraph.</p>
<p>This is another direct child paragraph.</p>
<div class="nested">
<p>This is a descendant paragraph, but not a direct child.</p>
</div>
<p>This is a third direct child paragraph.</p>
</div>
<div class="flex-container">
<div>
<h3>Descendant Selector</h3>
<p>Selects all <span class="highlight">p</span> elements inside <span class="highlight">.container</span>, regardless of nesting level.</p>
</div>
<div>
<h3>Direct Child Selector</h3>
<p>Selects only <span class="highlight">p</span> elements that are immediate children of <span class="highlight">.container</span>.</p>
</div>
</div>
</body>
</html>
Live view.
No comments to display
No comments to display