CSS Insights

1. element element & element > element'

1.1 element element

This styling will work on all child element that are nested under the parent element without considering the level of nesting.

<!-- HTML--> 
<div>
<span>
<p> Inside span 1 </p>
</span>
<span>
<p> Inside span 2 </p>
</span>
<span>
<p> Inside span 3 </p>
</span>
<span>
<p> Inside span 4 </p>
</span>
<p> Inside div and outside span </p>
</div>
/* Use this selector when you have to select all p elements inside a div regardless of their nesting level */ div p {
color: #ff7f50;
}

Output:

1.2 element > element

This styling will work for nested elements after writing the nested levels. The nested level can be reached by using >. To apply the styling to the <p> tag using > can be applied as:

div > span > p { color: #ff7f50; }

Output:

2. element + element & element ~ element

2.1 element + element

This styling will be applied to the first element that comes immediately after the other element. Here, p is the first element that comes immediately after div. We can also say that <p> is the immediate sibling of <div>.

Example:

<style> 
div + p {
color: green;
}
</style>
<body>
<div>
<span>
<p> Inside span 1 </p>
</span>
<span>
<p> Inside span 2 </p>
</span>
<span>
<p> Inside span 3 </p>
</span>
<span>
<p> Inside span 4 </p>
</span>
<p> Inside div and outside span </p>
</div>
<p> Outside div and Immediately after </p>
<p> Outside div and Not Immediately after</p>
</body>

Output:

2.1 element ~ element

To understand this, we changed our HTML. This style works on all elements which are the sibling of the other element. There is no need to be the immediate sibling in this case.

<!-- HTML --> 
<body>
<div>
<span>
<p> Inside span 1 </p>
</span>
<span>
<p> Inside span 2 </p>
</span>
<span>
<p> Inside span 3 </p>
</span>
<span>
<p> Inside span 4 </p>
</span>
<p> Inside div and outside span </p>
</div>
<p> Outside div and Immediately after </p>
<p> Outside div and Not Immediately after</p>
<span>
<p> Nested inside span</p>
</span>
<p> Not an immediate sibling </p>
</body>
div ~ p {
color: green;
}

Output:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aayush Arora

Aayush Arora

Google Developer Expert for Web Technologies, Co-founder https://filterpixel.com