Selecting Child Elements with CSS



The CSS child combinator is used to select all child elements of a parent element.

The syntax of the CSS child combinator is as follows −

Selector > Selector {
   attribute: /*value*/
}

The CSS descendant combinator is used to select all descendants of a parent element

The syntax of the CSS descendant combinator is as follows −

Selector Selector {
   attribute: /*value*/
}

Example

The following examples illustrate the CSS child and descendant combinator.

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
article > * {
   text-align: center;
   border: 10px groove tomato;
}
::first-line {
   box-shadow: inset 0 0 7px cornflowerblue;
}
</style>
</head>
<body>
<article>
<h2>Donec rutrum a erat vitae interdum. </h2>
<p>Duis consequat aliquet leo, quis aliquam ex vehicula in. Vivamus placerat tincidunt hendrerit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque semper ex eget nulla consectetur varius.</p>
<img src="https://images.unsplash.com/photo-1612840666989- a16302e84978?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=120&ixlib=rb1.2.1&q=80&w=120" />
</article>
</body>
</html>

Output

This will produce the following result −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
body > * {
   margin: 20px;
}
article p {
   font-size: 24px;
   box-shadow: -10px 1px 0 rgba(12,43,180, 0.6);
}
</style>
</head>
<body>
<article>
<p>Neque porro quisquam </p>
<p>est qui dolorem ipsum quia dolor sit amet,</p>
<div><p>consectetur, adipisci velit.....</p></div>
</article>
<div>
<p> consectetur, adipisci velit</p>
<article>
<p> consectetur, adipisci velit</p>
</article>
</div>
</body>
</html>

Output

This will produce the following result −


Advertisements