21.Aug.17

Pantaley Stoyanov

Pantaley Stoyanov

Code Bites: style "previous" HTML tags or how to reverse the cascading selectors without JavaScript

The idea of Cascading Style Sheets (CSS) is to have cascading style sheets. You can use combinations of CSS selectors to target siblings or child elements, but there is no “opposite” or “reverse” CSS selector to target parents.

The Issue

If you have two paragraphs, because of the cascading philosophy when you hover on the first one you can make changes on the second one, for example:

p:hover ~ p { color: red;}

But when you hover on the second, you can’t change styles on the first one.

The Solution

Of course, you can do everything with CSS with some tricks here and there.

In this example, we have 3 elements and we need to mute all except the hovered one.

Every time when you want to change any element which is above in the DOM Tree, try to target the parents. They are the key to select any element without using JavaScript.

See the Pen Style HTML elements when manipulating siblings with CSS by Pantaley (@pantaley) on CodePen.

Need consulting on this topic?

Yes No

Thank You! We will be in touch.