Home >Web Front-end >CSS Tutorial >How to smoothly transition both display and opacity properties in CSS animations?
Transitioning CSS Display and Opacity Properties
In CSS animations, it can be challenging to simultaneously transition both display and opacity properties. This becomes evident when attempting to make an element appear by modifying its display and opacity values upon hover, as seen in the given code snippet:
.child { opacity: 0; display: none; -webkit-transition: opacity 0.5s ease-in-out; -moz-transition: opacity 0.5s ease-in-out; transition: opacity 0.5s ease-in-out; } .parent:hover .child { opacity: 0.9; display: block; }
This code fails to transition the display property, resulting in an abrupt appearance of the element. To achieve a smooth transition for both properties, the following technique is recommended:
.parent:hover .child { display: block; -webkit-animation: fadeInFromNone 0.5s ease-out; -moz-animation: fadeInFromNone 0.5s ease-out; -o-animation: fadeInFromNone 0.5s ease-out; animation: fadeInFromNone 0.5s ease-out; } @-webkit-keyframes fadeInFromNone { 0% { display: none; opacity: 0; } 1% { display: block; opacity: 0; } 100% { display: block; opacity: 1; } } @-moz-keyframes fadeInFromNone { 0% { display: none; opacity: 0; } 1% { display: block; opacity: 0; } 100% { display: block; opacity: 1; } } @-o-keyframes fadeInFromNone { 0% { display: none; opacity: 0; } 1% { display: block; opacity: 0; } 100% { display: block; opacity: 1; } } @keyframes fadeInFromNone { 0% { display: none; opacity: 0; } 1% { display: block; opacity: 0; } 100% { display: block; opacity: 1; } }
This approach utilizes a CSS animation, fadeInFromNone, to control the transition of both properties. The animation starts with the element hidden and fully transparent (display: none; opacity:0). It then briefly makes the element visible but retains its transparency (display: block; opacity:0) to trigger the display transition. Finally, the element becomes fully visible and opaque (display: block; opacity:1). The transitions for display and opacity can be customized by adjusting the timing and easing functions in the animation rules.
The above is the detailed content of How to smoothly transition both display and opacity properties in CSS animations?. For more information, please follow other related articles on the PHP Chinese website!