Denis Potschien January 31st, 2013

CSS4 Today: Address Parent Elements Using cssParentSelector.js

CSS makes it easy to address child and sibling elements. Parent elements cannot be addressed by the use of CSS though, at least not today. CSS4 will introduce this possibility, but do not hope to see any browser supporting that any time soon. The jQuery plugin cssParentSelector allows the use of the new CSS4 parent selector today. cssParentSelector

Back to the Future: Plugin allows for a Glimpse of CSS4 right now

CSS4 will bring a plethora of improvements, some new selectors included. One of these new selectors ist the parent selector allowing for addressing parent elements which is not possible in CSS3. This is what the syntax will look like:
p! > input {
  color: red;
}
In our example the content of the P element gets colored red as soon as it is a parent of the, INPUT element. As no modern browser is able to display this effect, you would have to omit using it. If you do not want to wait for - say - three years, you should focus on cssParentSelector for jQuery. To use this plugin, you will call it as usual together with jQuery from the head of your HTML. The plugin will then care for all occurrances of the selector natively not supported. You are not limited in the use of the selector and are able to invoke it on classes and IDs. It is siupposed to work in combination with the universal selector also:
*! > p {
  background: green;
}
In this example the background of each parent of a P element will be colored green. Instead of addressing the parent element directly, you can as well aim at a special target element, which is child of the parent element:
!p label > input {
  color: blue;
}
In this example, the CSS property color affects all LABEL elements, which are child of the P element, if the P element is parent element of an INPUT element. Get the idea? Conclusion: The upcoming parent element will make lots of web developers happy. As long as it takes to get CSS4 going in common browsers, make use of cssParentSelector for jQuery. The plugin is available through Github and can be used free of charge for private and commercial projects under the MIT and GPL license. (dpe)

Denis Potschien

Denis works as a freelance web designer since 2005.

6 comments

  1. @Tom you have to rerun the script whenever a request is done because JavaScript wont recognize new DOM elements after the DOM is ready,

    @whatever-name-is-that I believe this will work on older version of IE, it needs jQuery and if you looked at the script it’s straightforward.

  2. It would be amazing if someone could invent a css previous adjacent sibling selector js polyfill like the one above. So that:

    !h4 + p {

    }

    would work.

Leave a Reply

Your email address will not be published. Required fields are marked *