What do the CSS selectors ~, +, and > do?
I have seen these selectors many times, but it is not clear what the main difference between them is. Can someone explain the difference between these symbols? When we should use these symbols?
What do the CSS selectors ~, +, and > do?
I have seen these selectors many times, but it is not clear what the main difference between them is. Can someone explain the difference between these symbols? When we should use these symbols?
Those are called combinators, discussed in the spec.
~
is the general sibling combinator. a ~ b
selects b
elements that are preceded (not necessarily immediately) by an a
element.
+
is the adjacent sibling combinator. a + b
selects b
elements immediately preceded by an a
element.
>
is the child combinator. a > b
selects b
elements that are immediate children of an a
element.
you can read this article which is having full information about css3 selector that you are searching for : http://www.codeproject.com/Articles/703826/CSS-Selector
article also having demo link where you can go and check what this selector is doing
HtmlElement ~ HtmlElemnt - Select all the html element which are precedes html element.
CSS
div ~ p
{
font:15px arial,sans-serif;
color:red;
}
Use
<div >
<p>My name is Pranay Rana.</p>
<span>
<p> data </p>
</span>
</div>
<p>I am working as Soft Engg.</p>
<p>My Demo Page.</p>
in this example p element which is precedes div get highlighted with read color, in this example "I am working as Soft Engg." and "My Demo Page." text get highlighted.
HtmlElement > HtmlElemnt - Select all the html element which are child of html element.
CSS
div > p
{
font:15px arial,sans-serif;
color:red;
}
Use
<div >
<p>My name is Pranay Rana.</p>
<Span>
<p> data </p>
</Span>
</div>
<p>I am working as Soft Engg.</p>
in this example all p element which are child of div get highlighted with read color, but p element which are not child of div doesnt get affected.
HtmlElement + HtmlElemnt - Select all the html element which are immediate after html element.
CSS
div + p
{
font:15px arial,sans-serif;
color:red;
}
Use
<div >
<p>My name is Pranay Rana.</p>
</div>
<p>I am working as Soft Engg.</p>
<p> data </p>
in this example p element which is immediate after div get highlighted with read color, in this example "I am working as Soft Engg." this text get highlighted.