We have learned about the child and descendant selectors in CSS. In this lesson, we shall learn about another type of selectors. The selectors resemble members of a family, so they are called sibling selector.
There are two types of sibling selectors in CSS, the adjacent sibling selector, and the general sibling selector.
An adjacent sibling selector only selects an element that is directly after another specific element. It uses the plus sign + to join the two elements together. The syntax is
element1+element2{ }
It means the selector targets the first element2 after any element1.
<!Doctype html> <html> <head> <title> Sibling Selector in CSS</title> <style type="text/css"> p+h2{ text-decoration:underline;color:red} </style> </head> <body> <p>We have learned about child and descendent selectors in previous lesson. In this lesson, we shall learn about another type of selector. It resembles members of a family, so it is called sibling selector. There are two types of sibling selectors, they are <h2>adjacent sibling selector </h2> and <h2>general sibling selector</h2></p> </body>
Notice that only the first h2 element was affected by p CSS styling, but the second h2 element is not affected.
A general sibling selector selects an element which may be directly or not directly after another specific element. It uses the tilde sign ~ to join the two elements together. The syntax is
element1~element2{ }
<!Doctype html> <html> <head> <title> Sibling Selector in CSS</title> <style type="text/css"> p~h2{ text-decoration:underline;color:red} </style> </head> <body> <p>We have learned about <h2>child and descendent selectors </h2>in previous lesson. In this lesson, we shall learn about another type of selector which also resembles members of a family, it is called sibling selector. There are two types of <h2>sibling selectors</h2>, they are <h2>adjacent sibling selector</h2> and <h2>general sibling selector</h2></p> </body> </html>
Notice that only the first and all subsequent h2 elements were affected by p css styling.
Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy