Home > Web Front-end > CSS Tutorial > Why Doesn't `DIV.section DIV:first-child` Only Style the First Direct Child?

Why Doesn't `DIV.section DIV:first-child` Only Style the First Direct Child?

Linda Hamilton
Release: 2024-12-18 22:39:20
Original
947 people have browsed it

Why Doesn't `DIV.section DIV:first-child` Only Style the First Direct Child?

Direct Child Selector Specificity

When applying CSS to HTML elements, it's crucial to understand the specificity of selectors. In your scenario, the selector DIV.section DIV:first-child appears to be styling both the "sub contents 1" and "header" divs.

However, the selector is intended to match only the first direct child of a div with the class "section". Let's break down why the original selector is not working as expected.

Understanding Direct Descendant vs. Direct Child

The :first-child pseudo-class selects the first child of an element. However, in your case, you're applying it to DIV.section DIV, which means "select all divs that are descendants of a div with the class 'section'". This includes both direct children and nested children.

Using the Direct Descendant Selector

To target only the first direct child of a div with the class "section", you should use the direct descendant selector (>). This operator matches elements that are immediate children of a specific parent. The modified selector would be:

div.section > div:first-child
Copy after login

This selector will correctly style only the "header" div, as it is the first immediate child of the div with the class "section".

Legacy Browser Issue

Note that the direct descendant selector is not supported in older browsers, such as Internet Explorer 6. If you need to support such browsers, you may need to use alternative methods, such as adding classes to the child divs.

The above is the detailed content of Why Doesn't `DIV.section DIV:first-child` Only Style the First Direct Child?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template