Can I apply a CSS transition on hover-out only? - css

The CSS transition property lets you animate on both hover-in & hover-out if you put the transition as below:
#inner{
opacity:0;
transition:opacity 2000ms;
}
#outer:hover #inner{
opacity:1;
}
However, if the transition is moved to :hover state, it only happens on hover-in.
#inner{
opacity:0;
}
#outer:hover #inner{
opacity:1;
transition:opacity 2000ms;
}
Is it possible to do the reverse, i.e. animate on hover-out only?

Here's one way to achieve this (put a bogus property none for transition property in :hover):
#inner2{
opacity:0;
transition:opacity 2000ms;
}
#outer:hover #inner2{
opacity:1;
transition:none;
}
http://jsfiddle.net/j716sbav/4/
Answer updated to incorporate #BoltClock's suggestion. Putting none instead of a bogus property is definitely more elegant.

If you prefer not to specify the transition property more than once, you can apply the transition to :not(:hover), but the caveat is that you need to swap all of the other declarations as well:
#inner2{
opacity:1;
}
#outer:not(:hover) #inner2{
opacity:0;
transition:opacity 2000ms;
}
Either of these will work, but if you don't want to deal with confusing inversions, stick with overriding via transition: none.
Also note that CSS selectors represent states and not events, which means that it utilizes a :hover state rather than mouseover and mouseout events; however, a transition from :hover to :not(:hover) is essentially the CSS way of expressing a mouseout animation.

I know this is a very old post but, as it came up in response to my Google search on the subject, I thought I'd post my solution.
After reading everything posted here, I found the simplest solution. Place a transition on the initial state as follows:
.btn {
opacity:0;
transition:0.6s;
}
.btn:hover {
opacity:1;
transition:0.8s;
}
So it has a transition time to the hover state and a transition time to the non-hover (ie normal) state. Saves a whole bunch of code.

Related

How can I animate my less from "display: block" to "display: none"?

I have a less file that hide and display an element like the following:
.cmp-accordion__panel {
&--hidden {
display: none;
}
&--expanded {
display: block;
-webkit-animation: slide-down 0.5s ease-out;
-moz-animation: slide-down 0.5s ease-out;
}
}
#-webkit-keyframes slide-down {
0% {
opacity: 0;
-webkit-transform: translateY(-5%);
}
100% {
opacity: 1;
-webkit-transform: translateY(0);
}
}
#-moz-keyframes slide-down {
0% {
opacity: 0;
-moz-transform: translateY(-5%);
}
100% {
opacity: 1;
-moz-transform: translateY(0);
}
}
In my JavaScript, I toggle the class name of the element between "cmp-accordion__panel--hidden" and "cmp-accordion__panel--expanded" if the event is triggered. I use keyframe and opacity to animate the transition from "display:none" to "display:block".
However, when I go from "display:block" to "display:none" to hide the element, the effect happens INSTANTLY. What should I add to animate the hiding?
As already said, is not possible animate or transition from display:block; to display: none; but this could be simulated in another way and is not necessary to use CSS animations, simply CSS transitions (in addition, is not necessary anymore to use vendor-prefixes to declare transitions or animations).
Please, look at this working example:
HTML (I inserted a fake content to create an element with a relative big height)
<div class="cmp-accordion__panel--expanded">
b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b
</div>
LESS
[class*="cmp-accordion__panel"] {
border:solid 1px red;
overflow:hidden;
transition:opacity 0.3s ease-out, max-height 0.8s ease-out;
}
.cmp-accordion__panel {
&--hidden {
max-height:0;
opacity:0;
}
&--expanded {
opacity:1;
max-height:1000px;
}
}
Please note that, thanks to attribute partial value selector I added also some rules that apply to both *--hidden and *--expanded classes (I personally prefer a general class and an addition of a second one in some cases, instead of switching between two, but I did not want to change too much your approach).
The key rule is switching between two values of max-height property, from a 0 value to another "enough big" one. If you effectively know final height of the element you can simply use also height property, but in case of dynamic content, max-height did the trick.
Please note also the presence of overflow:hidden; applied to both classes, to simulate height changes.
Finally, animation effect relies only on a CSS transition applied to opacity and max-height properties, with different timings to enhance effect.
You cannot animate or transition from display: block; to display: none;, so you will need to remove this if you wish to animate it.
To ensure it fades and is removed you should animate the visibilty and opacity attributes.
Alternatively if you are using jQuery you can use the .fadeOut() function.
MDN - CSS Visibility
jQuery - fadeOut()

Angular, change opacity property when ng-show/hide is included

when I include ng-show display property of css comes into effect but I want to change opacity property.
In the documentation of angular it is written defining your own custom css using important will override the effect but it is not working.
<p ng-show="registrationForm.firstname.$invalid" class="help-block colorred">Enter only alphabets</p>
<style>
.help-block.ng-show{ opacity:1 !important;}
.help-block.ng-hide{opacity:0 !important;}
I am new to angular.js.
Any kind of link or suggestion would be helpful
It is important to note that the animations are applied to the state of either ng-show or ng-hide, e.g. whether an element with ng-hide is currently hidden (resolves to true) or not (resolves to false), the same for an element with ng-show.
So, for an element with ng-hide, change your CSS to:
.help-block.ng-hide-add, .help-block.ng-hide-remove {
-webkit-transition:all linear 0.5s;
-moz-transition:all linear 0.5s;
-o-transition:all linear 0.5s;
transition:all linear 0.5s;
display:block!important;
}
.help-block.ng-hide-add.ng-hide-add-active,
.help-block.ng-hide-remove {
opacity:0;
}
.help-block.ng-hide-add,
.help-block.ng-hide-remove.ng-hide-remove-active {
opacity:1;
}
I had the same problem; ng-hide push a display none. It is possible to put a display on the css class ng-hide.
.help-block.ng-hide {
opacity: 0;
display:block !important;
}
About !important, there is in documentation :
By using !important, the show and hide behavior will work as expected despite any clash between CSS selector specificity.

How to display an element in the middle of CSS3 animation

In this example, I want to display the element just in a step of the animation. However, it is not possible, because if I set display:none in the main CSS rule, the animation will not override it.
#test {
-webkit-animation: test 2s;
display:none; // here is the problem, as the animation does not override it.
}
#-webkit-keyframes test {
0%{margin:5px}
20%{display:block}
70%{margin:40px}
}
Note that this is a simplified example, and in practice, I need to use display:none to hide the element before it becomes visible by the animation. Thus, other tricks like opacity does not satisfy my need.
I'm not sure what you're trying to do, if you want to hide the element and just show it when the animation starts, make use of visibility property like this:
#test {
-webkit-animation: test 2s;
visibility:hidden;
}
#-webkit-keyframes test {
0%{margin:5px}
20%{visibility:visible}
70%{margin:40px}
}
fiddle example

Use cases for CSS transitions and CSS animations

As far as I understand, there is no such thing we can implement using css transitions, but we can not to implement using css animations, but not vice versa.
That is, any transition has a css animation equivalent.
For example, this one
.ablock:hover {
position: relative;
-moz-transition-property: background-color, color;
-moz-transition-duration: 1s;
-webkit-transition-property: background-color, color;
-webkit-transition-duration: 1s;
color: red;
background-color:pink;
}
is an equivalent of following:
.ablock:hover {
-moz-animation-duration:1s;
-moz-animation-name:transition;
-webkit-animation-duration:1s;
-webkit-animation-name:transition;
}
#-moz-keyframes transition {
to {
color: red;
background-color: pink;
}
}
#-webkit-keyframes transition {
to {
color: red;
background-color: pink;
}
}
My question is - if we a talking about browser supporting both css transitions and animations, what are use cases for choosing one or another approach?
As for transitions, I can name only one - they have more succinct syntax, we don't have to copy paste huge chucks of code for #-moz-keyframes, #-webkit-keyframes and so on.
As for control from javascript, flexibility and complexity animations are much more appropriate tool (at least, at first glance). So, what are use cases?
UPD:
OK, let me try to list interesting info found in questions.
This one is contributed by Roman Komarov. Say, we have a div and child div. While parent div is hovered, we are transitioning the child element. Once we are taking away the mouse, transition is cancelled. Duration of this cancellation is exactly the time we've already spend for transitioning. Animation is cancelled "immediately". I don't know, nevertheless, how standard are those two behaviours.
Animations can be looped (and there can be keyframes, yeeah).
Transitions can be more flexible and you can easily make transitions to different values and in different circumstances.
While you can emulate some transitions by animations (like you mentioned in your post), the transitions are just more powerful:
You just tell which properties you must animate and in which conditions (using the different selectors)
You can trigger the transition in different ways:
Changing properties in CSS for pseudo-classed :hover, :active etc. (Creating pure CSS UI)
Changing properties in different classes for different purposes.
Changing properties in inline styles: in conjunction with JS it's just more powerful than animations.
With transitions you are able to transition between any value of the defined property, which you want to be transitioned. As an example, you want to transition the color of a link, when it's hovered and active:
a {
color: #000;
transition: color .4s ease;
}
a:hover {
color: #888;
}
a:active {
color: #faa;
}
You are independent, which color you choose.
Now if you want to use the animation style, you have to explicitly set the color value for the animation states. And you are not able to easily animate between the three states: normal, hover and active. You need more complex definitions. I'll try this one with animations:
a {
color: #000;
animation-duration: 0.4s;
animation-fill-mode: forwards;
animation-name: toDefault;
}
a:hover {
animation-duration: 0.4s;
animation-fill-mode: forwards;
animation-name: toHover;
}
a:active {
animation-duration: 0.4s;
animation-fill-mode: forwards;
animation-name: toActive;
}
#keyframes toDefault {
to {
color: #000;
}
}
#keyframes toHover {
to {
color: #888;
}
}
#keyframes toActive {
to {
color: #faa;
}
}
Now this does not include the animation back to the state before. I'm not sure if you can even fetch that.
So in short: with transitions you are able to animate an undefined set of properties and values, whilst keyframe animations are used for well defined animations and/or transitions.

css3 transition animation on load?

Is it possible to use CSS3 transition animation on page load without using Javascript?
This is kind of what I want, but on page load:
image-slider.html
What I found so far
CSS3 transition-delay, a way to delay effects on elements. Only works on hover.
CSS3 Keyframe, works on load but are extremly slow. Not useful because of that.
CSS3 transition is fast enough but don't animate on page load.
You can run a CSS animation on page load without using any JavaScript; you just have to use CSS3 Keyframes.
Let's Look at an Example...
Here's a demonstration of a navigation menu sliding into place using CSS3 only:
#keyframes slideInFromLeft {
0% {
transform: translateX(-100%);
}
100% {
transform: translateX(0);
}
}
header {
/* This section calls the slideInFromLeft animation we defined above */
animation: 1s ease-out 0s 1 slideInFromLeft;
background: #333;
padding: 30px;
}
/* Added for aesthetics */ body {margin: 0;font-family: "Segoe UI", Arial, Helvetica, Sans Serif;} a {text-decoration: none; display: inline-block; margin-right: 10px; color:#fff;}
<header>
Home
About
Products
Contact
</header>
Break it down...
The important parts here are the keyframe animation which we call slideInFromLeft...
#keyframes slideInFromLeft {
0% {
transform: translateX(-100%);
}
100% {
transform: translateX(0);
}
}
...which basically says "at the start, the header will be off the left hand edge of the screen by its full width and at the end will be in place".
The second part is calling that slideInFromLeft animation:
animation: 1s ease-out 0s 1 slideInFromLeft;
Above is the shorthand version but here is the verbose version for clarity:
animation-duration: 1s; /* the duration of the animation */
animation-timing-function: ease-out; /* how the animation will behave */
animation-delay: 0s; /* how long to delay the animation from starting */
animation-iteration-count: 1; /* how many times the animation will play */
animation-name: slideInFromLeft; /* the name of the animation we defined above */
You can do all sorts of interesting things, like sliding in content, or drawing attention to areas.
Here's what W3C has to say.
Very little Javascript is necessary:
window.onload = function() {
document.body.className += " loaded";
}
Now the CSS:
.fadein {
opacity: 0;
-moz-transition: opacity 1.5s;
-webkit-transition: opacity 1.5s;
-o-transition: opacity 1.5s;
transition: opacity 1.5s;
}
body.loaded .fadein {
opacity: 1;
}
I know the question said "without Javascript", but I think it's worth pointing out that there is an easy solution involving one line of Javascript.
It could even be inline Javascript, something like that:
<body onload="document.body.className += ' loaded';" class="fadein">
That's all the JavaScript that's needed.
I think I have found a sort of work around for the OP question - instead of a transition beginning 'on.load' of the page - I found that using an animation for an opacity fade in had the same effect, (I was looking for the same thing as OP).
So I wanted to have the body text fade in from white(same as site background) to black text colour on page load - and I've only been coding since Monday so I was looking for an 'on.load' style thing code, but don't know JS yet - so here is my code that worked well for me.
#main p {
animation: fadein 2s;
}
#keyframes fadein {
from { opacity: 0}
to { opacity: 1}
}
And for whatever reason, this doesn't work for .class only #id's(at least not on mine)
Hope this helps - as I know this site helps me a lot!
CSS only with a delay of 3s
a few points to take here:
multiple animations in one call
we create a wait animation that just delays the actual one (the second one in our case).
Code:
header {
animation: 3s ease-out 0s 1 wait, 0.21s ease-out 3s 1 slideInFromBottom;
}
#keyframes wait {
from { transform: translateY(20px); }
to { transform: translateY(20px); }
}
#keyframes slideInFromBottom {
from { transform: translateY(20px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
Well, this is a tricky one.
The answer is "not really".
CSS isn't a functional layer. It doesn't have any awareness of what happens or when. It's used simply to add a presentational layer to different "flags" (classes, ids, states).
By default, CSS/DOM does not provide any kind of "on load" state for CSS to use. If you wanted/were able to use JavaScript, you'd allocate a class to body or something to activate some CSS.
That being said, you can create a hack for that. I'll give an example here, but it may or may not be applicable to your situation.
We're operating on the assumption that "close" is "good enough":
<html>
<head>
<!-- Reference your CSS here... -->
</head>
<body>
<!-- A whole bunch of HTML here... -->
<div class="onLoad">OMG, I've loaded !</div>
</body>
</html>
Here's an excerpt of our CSS stylesheet:
.onLoad
{
-webkit-animation:bounceIn 2s;
}
We're also on the assumption that modern browsers render progressively, so our last element will render last, and so this CSS will be activated last.
add this to your css for fade in animation
body{animation: 2s ease-out 0s 1 FadeIn;}
#keyframes FadeIn {
0% {
opacity:0;
}
100% {
opacity:1;
}
}
increase the ease-out time if you want it to load slower
Even simplier solution (still with [one line inline] javascript):
Use this as the body tag:
Note that body. or this. did not work for me. Only the long ; querySelector allow the use of classList.remove (Linux Chromium)
<body class="onload" onload="document.querySelector('body').classList.remove('onload')">
and add this line on top of your other css rules.
body.onload *{ transform: none !important; }
Take note that this can apply to opacity (as requested by OP [other posters] ) simply by using opacity as a transition trigger instead. (might even work on any other css ruling in the same fashion and you can use multiple class for explicity delay between triggering)
The logic is the same. Enforce no transform (with :none !importanton all child element of body.onloadand once the document is loaded remove the class to trigger all transition on all elements as specified in your css.
FIRST ANSWER BELOW (SEE EDIT ABOVE FOR SHORTER ANSWER)
Here is a reverse solution:
Make your html layout and set the css accordingly to your final result (with all the transformation you want).
Set the transition property to your liking
add a class (eg: waitload) to the elements you want to transform AFTER load. The CSS keyword !important is the key word here.
Once the document is loaded, use JS to remove the class from the elements to to start transformation (and remove the transition: none override).
Works with multiple transition on multiple elements. Did not try cross-browser compatibility.
div {
width: fit-content;
}
#rotated {
transform: rotate(-50deg)/* any other transformation */
;
transition: 6s;
}
#translated {
transform: translate(90px)/* any other transformation */
;
transition: 6s;
}
.waitload {
transform: none !important;
}
<div id='rotated' class='waitload'>
rotate after load
</div>
<div id='translated' class='waitload'>
trasnlate after load
</div>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', init);
function init() {
[...document.querySelectorAll('.waitload')]
.map(e => e.classList.remove('waitload'));
}
</script>
Similar to #Rolf's solution, but skip reference to external functions or playing with class. If opacity is to remain fixed to 1 once loaded, simply use inline script to directly change opacity via style. For example
<body class="fadein" onload="this.style.opacity=1">
where CSS sytle "fadein" is defined per #Rolf,defining transition and setting opacity to initial state (i.e. 0)
the only catch is that this does not work with SPAN or DIV elements, since they do not have working onload event
start it with hover of body than It will start when the mouse first moves on the screen, which is mostly within a second after arrival, the problem here is that it will reverse when out of the screen.
html:hover #animateelementid, body:hover #animateelementid {rotate ....}
thats the best thing I can think of: http://jsfiddle.net/faVLX/
fullscreen: http://jsfiddle.net/faVLX/embedded/result/
Edit see comments below:
This will not work on any touchscreen device because there is no hover, so the user won't see the content unless they tap it. – Rich Bradshaw
Ok I have managed to achieve an animation when the page loads using only css transitions (sort of!):
I have created 2 css style sheets:
the first is how I want the html styled before the animation...
and the second is how I want the page to look after the animation has been carried out.
I don't fully understand how I have accomplished this but it only works when the two css files (both in the head of my document) are separated by some javascript as follows.
I have tested this with Firefox, safari and opera. Sometimes the animation works, sometimes it skips straight to the second css file and sometimes the page appears to be loading but nothing is displayed (perhaps it is just me?)
<link media="screen,projection" type="text/css" href="first-css-file.css" rel="stylesheet" />
<script language="javascript" type="text/javascript" src="../js/jQuery JavaScript Library v1.3.2.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
// iOS Hover Event Class Fix
if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) ||
(navigator.userAgent.match(/iPad/i))) {
$(".container .menu-text").click(function(){ // Update class to point at the head of the list
});
}
});
</script>
<link media="screen,projection" type="text/css" href="second-css-file.css" rel="stylesheet" />
Here is a link to my work-in-progress website: http://www.hankins-design.co.uk/beta2/test/index.html
Maybe I'm wrong but I thought browsers that do not support css transitions should not have any issues as they should skip straight to the second css file without delay or duration.
I am interested to know views on how search engine friendly this method is. With my black hat on I suppose I could fill a page with keywords and apply a 9999s delay on its opacity.
I would be interested to know how search engines deal with the transition-delay attribute and whether, using the method above, they would even see the links and information on the page.
More importantly I would really like to know why this is not consistent each time the page loads and how I can rectify this!
I hope this can generate some views and opinions if nothing else!
If anyone else had problems doing two transitions at once, here's what I did. I needed text to come from top to bottom on page load.
HTML
<body class="existing-class-name" onload="document.body.classList.add('loaded')">
HTML
<div class="image-wrapper">
<img src="db-image.jpg" alt="db-image-name">
<span class="text-over-image">DB text</span>
</div>
CSS
.text-over-image {
position: absolute;
background-color: rgba(110, 186, 115, 0.8);
color: #eee;
left: 0;
width: 100%;
padding: 10px;
opacity: 0;
bottom: 100%;
-webkit-transition: opacity 2s, bottom 2s;
-moz-transition: opacity 2s, bottom 2s;
-o-transition: opacity 2s, bottom 2s;
transition: opacity 2s, bottom 2s;
}
body.loaded .text-over-image {
bottom: 0;
opacity: 1;
}
Don't know why I kept trying to use 2 transition declarations in 1 selector and (not really) thinking it would use both.
You could use custom css classes (className) instead of the css tag too.
No need for an external package.
import React, { useState, useEffect } from 'react';
import { css } from '#emotion/css'
const Hello = (props) => {
const [loaded, setLoaded] = useState(false);
useEffect(() => {
// For load
setTimeout(function () {
setLoaded(true);
}, 50); // Browser needs some time to change to unload state/style
// For unload
return () => {
setLoaded(false);
};
}, [props.someTrigger]); // Set your trigger
return (
<div
css={[
css`
opacity: 0;
transition: opacity 0s;
`,
loaded &&
css`
transition: opacity 2s;
opacity: 1;
`,
]}
>
hello
</div>
);
};
Not really, as CSS is applied as soon as possible, but the elements might not be drawn yet. You could guess a delay of 1 or 2 seconds, but this won't look right for most people, depending on the speed of their internet.
In addition, if you want to fade something in for instance, it would require CSS that hides the content to be delivered. If the user doesn't have CSS3 transitions then they would never see it.
I'd recommend using jQuery (for ease of use + you may wish to add animation for other UAs) and some JS like this:
$(document).ready(function() {
$('#id_to_fade_in')
.css({"opacity":0}) // Set to 0 as soon as possible – may result in flicker, but it's not hidden for users with no JS (Googlebot for instance!)
.delay(200) // Wait for a bit so the user notices it fade in
.css({"opacity":1}); // Fade it back in. Swap css for animate in legacy browsers if required.
});
Along with the transitions added in the CSS. This has the advantage of easily allowing the use of animate instead of the second CSS in legacy browsers if required.

Resources