CSS Descendant Selector - Child vs Descendant selector
What is CSS Descendant Selector?
CSS Descendant Selector match all element that are descendants of specified element.
CSS Descendant Selector identify by whitespace between two selector element.
CSS Descendant Selector select specific element and that specific element match all descendants element.
Syntax
This syntax apply to match all <p> element that are descendants of specified element.
div p {
property: value;
property: value;
...
}
Same as this syntax apply to match all element that are descendants of specified <div> element.
div * {
property: value;
property: value;
...
}
Example
Match all <p> element that are descendants of <div> to apply CSS.
<!DOCTYPE html>
<html>
<head>
<title>CSS Descendant Selector</title>
<style>
div p {
font-size:24px;
}
</style>
</head>
<body>
<p>This is paragraph text</p>
<h4>This is h4 heading text</h4>
<p>This is another paragraph text</p>
</body>
</html>
Example
In this example selector div * matches all descendant element of specified <div> element.
<!DOCTYPE html>
<html>
<head>
<title>CSS Descendant Selector</title>
<style>
div * {
font-size:24px;
}
</style>
</head>
<body>
<p>This is paragraph text</p>
<h4>This is h4 heading text</h4>
<p>This is another paragraph text</p>
</body>
</html>
Difference between Descendant and Child Selectors
Descendant selector is select child of child of so forth child element where else Child selector is only of that child of specific element.
Following example all <p> element whose are descendant of div element
Example
Select all element whose have child of an <ul> element.
<!DOCTYPE html>
<html>
<head>
<title>CSS Descendant Selector</title>
<style>
div p {
font-size:24px;
}
</style>
</head>
<body>
<div>
<p>Child Selector</p>
<div>
<p>Descendant Selector</p>
</div>
<h4>Child Selector</h4>
<p>Child Selector</p>
</div>
</body>
</html>
Browser Compatibility
- Google Chrome 2+
- Mozilla Firefox 1+
- Internet Explorer 8+
- Opera 9.2+
- Safari 1.3+
Note: Here details of browser compatibility with version number may be this is bug and not supported. But recommended to always use latest Web browser.