user4103106
user4103106

Reputation: 41

CSS Transition is not working

I have just started learning CSS transitions from here. But the code doesn't work. I am executing on Firefox in Ubuntu.

index.html:

<!DOCTYPE html>
<html>
<head>
<title>Animation</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="image1">
<img  src="image.jpg" height="150" width="150" />
</div>
</body>
</html>

style.css:

#image1 {
-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;
}

I get only the image but not the transition. Also, how do I make the transition run on a button click?

Upvotes: 0

Views: 95

Answers (2)

Ian Hazzard
Ian Hazzard

Reputation: 7771

Make sure that you change the css values, or there will be nothing to animate. You can put the values of the image under the :hover selector, like this:

#image1 {
width:20px;
height:20px;
-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;
}

#image1:hover {
width:200px;
height:200px;
-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;
}
<!DOCTYPE html>
<html>
<head>
<title>Animation</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<img  src="image.jpg" height="150" width="150" id="image1"/>
</body>
</html>

For more information about animations and for some good practice, visit W3Scools.com.

Upvotes: 1

dfsq
dfsq

Reputation: 193251

By definition the word "transition" means change of state from one into another. CSS transition thus will only run once you change some CSS property. For example you can change some styles on mouseover with :hover pseudo class or by changing class name. For example:

var image = document.getElementById('image1');

document.querySelector('button').onclick = function() {
    image.className = image.className === 'active' ? '' : 'active';
};
#image1 {
    border: 4px #DDD solid;
    -webkit-transition: all 1s ease-in-out;
    transition: all 1s ease-in-out;
}
#image1:hover,
#image1.active:hover {
    border-color: purple;
    border-width: 4px;
}

#image1.active {
    border-color: coral;
}
<img src="http://lorempixel.com/100/100" id="image1" height="150" width="150" />

<button>Run</button>

Notes

1). You don't need to define vendor prefixes for transition, since support is already pretty good.

2). Of course instead of all keyword in transition rule you can define a specific property to animate:

#image1 {
    opacity: 0.5;
    transition: opacity 1s ease-in-out;
}
#image1:hover {
    opacity: 1;
}

3). Read about CSS Transitions more at MDN.

Upvotes: 3

Related Questions