Вопрос

I have an element with two classes:

<div class="class1 class2"></div>

.class1 {transition: background-color 0.4s;}
.class2 {transition: top 1s;}

The problem is that the transition of class2 overwrites the transition of class1.

I can't use .class2 {transition: all 1s} because the transition duration must be different.

I also don't want to duplicate the code from class1 to class2 because class2 can be applied to other elements as well.

Is there a way to add transitions to an element without overwriting existing ones?

Это было полезно?

Решение

Unfortunately it's not possible to "extend" a property in another rule in CSS, no matter if it's a transition or another property. Some alternatives may be:

Creating a rule for the combination of the classes

.class1.class2 {transition:background-color 0.4s, top 1s;}

The cons are that you have to create such rule for each of the relevant combinations. This also means code duplication.

Changing the html to eliminate the need to combine the rules

Find a proper way of representing the html objects so you won't need to extend the rules. In my case it's:

<div class="class2">
  <div class="class1">
</div>

The cons are a bit more complicated html. On the other hand you avoid duplicate code, and make your css more reusable.

Другие советы

You can use a selector which is a combination of the two classes, and separate the two transitions with a comma, like this:

.class1.class2 { 
    -webkit-transition: background-color 0.4s, top 1s; /* Safari 4.0 */
    -moz-transition: background-color 0.4s, top 1s; /* FF 5.0 */
    -o-transition: background-color 0.4s, top 1s; /* Opera 12 */
    transition: background-color 0.4s, top 1s; /* Modern browsers */
}

In CSS, when there are two conflicting properties, the last one will always overwrite the first one (unless you add "!important" to it which, in my opinion is a little lazy).

You want to consider re-thinking the way the CSS flows. The most important styles you want your element to always have should be in the first block... and subsequent styles should be applied in an additive fashion.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top