Home >Web Front-end >CSS Tutorial >How to Select Only the Direct Child of a DIV Using CSS?
CSS Selector for Direct Child
You want to apply CSS to the first direct child of a DIV with the class "section." However, you're encountering an unexpected behavior where the style is affecting more than just the desired element.
The selector you used is "DIV.section DIV:first-child." This selector matches any DIV that is inside a DIV with the class "section" and is the first child of its parent. However, in your HTML, the "sub contents 1" DIV is inside another DIV that is the first child of the "section" DIV, hence the unexpected application of the style.
To resolve this, you can use a more precise selector:
For Both Children of the Main DIV:
div.section > div
This selector uses the ">" symbol, which selects elements that are direct children of the specified parent. In this case, it will only match the two DIVs that are direct children of the "section" DIV.
For Only the Header:
div.section > div:first-child
This selector combines the previous one with the ":first-child" pseudo-class, ensuring that only the first direct child of the "section" DIV is selected. This will target the "header" DIV exclusively.
Note that the ">" symbol is supported by all major browsers except IE6. If IE6 support is crucial, you may need to use an alternative approach like adding classes to the child DIVs and styling them directly.
The above is the detailed content of How to Select Only the Direct Child of a DIV Using CSS?. For more information, please follow other related articles on the PHP Chinese website!