Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a CSS selector reference another selectors property?

I've just noticed that Webkit now has some support regarding the CSS Values and Units Module Level spec. And I was wondering if anyone knows if there is a way to reference another CSS selectors (or DOM style) property from a CSS selector?

I'm expecting something like this to be the answer here. Which I know is most likely the case for current browser implementations; but please keep reading...

For instance, in the case where an animation might resize an element (NOTE the ${.element2.width} is fictitious syntax):

<style type="text/css">
.element1 {
  .width: /*-webkit-,-o-,-moz-*/calc(80% - ${.element2.width});
}
.element2 {
  .width: 100px;
}
.element2:hover {
  width: 200px;
  transition: all 0.4s ease-in-out;
}
</style>

In this case I would expect the .element1's width to be re-evaluated based off the transition triggered from the hover events on .element2.

I realize that the aforementioned spec. is only a working draft but perhaps the syntax for referring to such a 'referential selector property' is defined within another spec. which I'm yet to discover? Or simply just not a case for concern (thanks to an overlooked work around)?

like image 520
Benjamin Conlan Avatar asked Jun 17 '12 13:06

Benjamin Conlan


2 Answers

I added an answer to the question you linked: https://stackoverflow.com/a/11071806/137626

  • You can use the same declaration block with as many selectors as you want by grouping them (selectors are separated by commas)
  • You can't reuse the same declaration block later with a different CSS selector without rewriting the whole declaration block preceded by this selector or using a preprocessor/macro that'll do that for you. Or add it to the existing declaration block as above

Now with your example of an element resized by CSS itself: you could use CSS3 Media Queries and its @media rules containing as many declaration blocks as you want. These media queries would adapt to the width of viewport here.
Mixing expanding elements via animation and media queries that would've the reverse effect will be very soon very complicated (and I'll wonder what content you're playing with); if you want to Keep It Simple, then JS is the way to go. There are variables, loops, events ;) and you can start a CSS3 animation by adding or removing a single class from an element (or whatever CSS selector).
CSS3 won't replace JS (and you shouldn't use JS to style HTML as JS isn't activated or existing everywhere and there's already a nice fallback named CSS).

like image 109
FelipeAls Avatar answered Oct 12 '22 14:10

FelipeAls


Other than using a pre-compiler such as sass/scss or less, I believe all you can do is wait or hard-code it.

like image 20
Fewfre Avatar answered Oct 12 '22 14:10

Fewfre