0

Is there any way to have

a CSS selector "inherit" all declarations from another selector?

For example, imagine I have some simple img transformation rules:

.tilt {
  -webkit-transition: all 0.5s ease;
     -moz-transition: all 0.5s ease;
       -o-transition: all 0.5s ease;
      -ms-transition: all 0.5s ease;
          transition: all 0.5s ease;
}

.tilt:hover {
  -webkit-transform: rotate(-10deg);
     -moz-transform: rotate(-10deg);
       -o-transform: rotate(-10deg);
      -ms-transform: rotate(-10deg);
          transform: rotate(-10deg);
}

Is there any way to do the following?

body.home.page .box-2 figure img {
    /* inherit from .tilt */
}

body.home.page .box-2 figure img:hover {
    /* inherit from .tilt:hover */
}

I realize that I could do this simply by adding the "tilt" class to the img tag if I had access to the underlying code, but I don't. I also know I could use javascript to add the tilt class to the img tag at runtime, but all I have access to change is the CSS.

Basically, I want to conserve code by not having to repeat these declarations over and over again in the CSS file. Is there any way to do this? Again, I only have access to the CSS file, nothing else.

Doug
  • 5,116
  • 10
  • 33
  • 42
  • 1
    If I understand what you're really trying to do, the kind of actual inheritance or nesting (not just grouping) you're talking about is not possible with plain CSS. People often use a [CSS preprocessor](http://blog.teamtreehouse.com/how-to-choose-the-right-css-preprocessor) like LESS or SASS to help with this. – jfriend00 Mar 28 '14 at 04:17
  • Another strike against CSS. One fights against the dom to override inheritance with silly little gotchas like "!important" trying to bang things in the place but you can't specify inheritance in css. – eggmatters Oct 24 '14 at 20:30

3 Answers3

3

You could use multiple selectors. Separate them with a comma.

.tilt,
body.home.page .box-2 figure img {
  -webkit-transition: all 0.5s ease;
     -moz-transition: all 0.5s ease;
       -o-transition: all 0.5s ease;
      -ms-transition: all 0.5s ease;
          transition: all 0.5s ease;
}

You can't actually use syntax like you described, unless you use a CSS pre-processor.

alex
  • 479,566
  • 201
  • 878
  • 984
0

Yes, this is possible with grouping in CSS as follows:

.tilt , body.home.page .box-2 figure img {.....}

.tilt:hover,body.home.page .box-2 figure img:hover{...}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
pj013
  • 1,393
  • 1
  • 10
  • 28
0

No, selectors do not inherit anything. Properties of elements inherit values from parent elements.

Regarding to what seems to be the intended question (as opposite to the question asked), it is about organizing your markup and CSS, and quite often, the approach suggested by @alex solves the problem nicely.

Jukka K. Korpela
  • 195,524
  • 37
  • 270
  • 390