Descendent selector allows you to apply styles to elements that are children, grandchildren, or any level of descendant within a specified ancestor. This selector is particularly useful when you want to style elements based on their hierarchy in the HTML structure.
Syntax
ancestor descendant { /* CSS properties */ }
Here, ancestor is the element containing the descendant element(s) you want to style. The descendant element is the one you want to target for styling. The key point is that the descendant can be any level of nested inside the ancestor.
Let’s consider an example where we have an unordered list (<ul>) with list items (<li>). We want to apply specific styles to all the list items within the unordered list.
descendentSelector.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Descendant Selector Example</title> <link rel="stylesheet" href="../../css/selectors/descendentSelector.css"> </head> <body> <ul> <li>Home</li> <li>About <ol> <li>Our Team</li> <li>Our History</li> </ol> </li> <li>Services <ol> <li>Customer Care</li> <li>Health</li> <li>Finance</li> </ol> </li> <li>Contact</li> </ul> </body> </html>
descendentSelector.css
ul li { color: darkblue; font-weight: bold; margin-bottom: 5px; }
Open ‘descendentSelector.html’, you will see below screen.
In this example, we have an unordered list (<ul>) with several list items (<li>), including nested list items within a sublist. The 'ul li' selector targets all li elements that are descendants of a ul element, regardless of how deeply they are nested. The CSS applies a dark blue color, bold font weight, and a margin to the bottom of each list item.
When the CSS is applied, every list item within any unordered list on the page will appear with the specified styles. This includes both the top-level list items (like "Home" and "Services") and the nested list items (like "Our Team" and "Our History").
No comments:
Post a Comment