CSS Combinators
CSS Combinators clarify the relationship between two selectors, The selectors in CSS are used to select the content for styling.
Four types of combinators:
- General sibling selector (~)
- Adjacent sibling selector (+)
- Child selector (>)
- Descendant selector (space)
General Sibling Selector (~):
Selects all elements that are siblings of a specified element.
Example:
<!DOCTYPE html> <html> <head> <title>General Sibling Selector</title> <style> body{ text-align: center; } h1 ~ p{ color: blue; font-size: 25px; font-weight: bold; text-align: center; } div { font-size: 32px; } </style> </head> <body> <h1>General sibling selector (~) property</h1> <p>It is the first paragraph element which will get effected.</p> <div> It is the div element </div> </body> </html>
OUTPUT:
Adjacent Sibling Selector (+):
“adjacent” means “immediately following”.
Example:
<!DOCTYPE html> <html> <head> <title> Adjacent Sibling Selector </title> <style> body{ text-align: center; } p + p{ color: Blue; font-size:25px; font-weight: bold; text-align: center; } p { font-size: 32px; } </style> </head> <body> <h1> Adjacent sibling selector (+) property</h1> <p> It is the first paragraph </p> <p> It is the second paragraph which is immediately next to the first paragraph, and it get selected. </p> <div> This is the div element </div> </body> </html>
OUTPUT:
Child Selector (>):
All elements that are the children of a specified element.
Example:
<!DOCTYPE html> <html> <head> <title> Child Selector </title> <style> body{ text-align: center; } div > p{ color: Blue; font-size:25px; font-weight:bold; text-align:center; } p { font-size: 20px; } </style> </head> <body> <h1> Child selector (>) property</h1> <p> It is the first paragraph </p> <p> It is the second paragraph </p> <div> <h1>This is the div element</h1> <p> This is the third paragraph which is the child of div element </p> <p> This is the fourth paragraph and also get selected because it is also the child of div element </p> </div> </body> </html>
OUTPUT:
Descendant Selector (space):
All elements that are descendants of a specified element.
Example:
<!DOCTYPE html> <html> <head> <title> Descendant Selector </title> <style> body{ text-align: center; } div p{ color: blue; font-size:28px; font-weight: bold; text-align: center; } p,div { font-size: 25px; } </style> </head> <body> <div> <p> This is 1st paragraph in the div. </p> <p> This is 2nd paragraph in the div. </p> <span> This is the span element in the div <p> This is the paragraph in the span. It will also be affected. </p> </span> </div> <p> Paragraph 4. It will not be affected because it is not in the div. </p> </body> </html>
OUTPUT: