CSS Combinators
CSS Combinators
There are four types of combinators in CSS that are listed as follows:
Program:
<!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
<p> It is the paragraph under the div element </p>
</div>
<p>It is the paragraph element after the div</p>
<p>It is the paragraph element which will also get affected</p>
</body>
</html>
Syntax
element + element {
/*style properties*/
}
Program:
<!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>
<p> This is the third paragraph which does not get affected </p>
<p> This paragraph is also selected because it immediately next to third paragraph </p>
</body>
</html>
It selects the direct descendant of the parent. This combinator only matches the elements that are the immediate child in the
document tree.
Syntax
element > element {
/*style properties*/
}
Program:
<!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>
/*style properties*/
}
by using <div>
div p {
/*style properties*/
}
Program:
<!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>