The Transition Property in CSS3 With Examples
CSS3 makes it possible to easily create animations for hover events.
In a previous post, we explained how the hover.css library works and gave a demo of several options.
In this tutorial, we’ll give you some basic examples of the transition property to do fade effects for your links. We’ll do this by adding in other CSS properties such as color and border.
Step 1: The CSS file
Create a CSS file and add the following code:
{codecitation css}.ost-transition{
transition:All 1s ease;
-webkit-transition:All 1s ease;
-moz-transition:All 1s ease;
-o-transition:All 1s ease;
}{/codecitation}
In the previous code, we use 4 lines to specify the same property to support different browsers:
- transition: default
- -webkit-transition: Chrome and Safari
- -moz-transition: Firefox
- -o-transition: Opera
The 3 parameters from the value are:
- Property: All. Another example: color.
- Duration: 1s. Means 1 second.
- Timing function: ease. Another example: linear.
The transition property is set as all to dynamically use the available ones later in a separate class.
In the same CSS file, also add the following code:
{codecitation css}.ost-opacity:hover{
opacity: 0.3;
}
.ost-color:hover{
color: #fff;
background: #2184cd;
}
.ost-padding:hover{
padding: 15px 20px;
}
.ost-border:hover{
border: 2px solid #000;
}{/codecitation}
The previous code include custom classes to set specific properties that will work when user hover an element.
Step 2: The HTML file
Create an HTML file, inside the head tag load the CSS from step 1:
{codecitation html}<link type=”text/css” href=“path/to/your/file.css” rel=”stylesheet” />{/codecitation}
Step 3: The effects
In your HTML file add the following code inside your body tag to get different results when you place the cursor over the link:
Opacity. Use class ost-opacity
{codecitation html}<p><a class=”ost-transition ost-opacity” href=”#”>Opacity</a></p>{/codecitation}
Color. Use class ost-color
{codecitation html}<p><a class=”ost-transition ost-color” href=”#”>Color</a></p>{/codecitation}
Padding. Use class ost-padding
{codecitation html}<p><a class=”ost-transition ost-padding” href=”#”>Padding</a></p>{/codecitation}
Border. Use class ost-border
{codecitation html}<p><a class=”ost-transition ost-border” href=”#”>Border</a></p>{/codecitation}
Color, Padding and Border. You can mix the CSS classes to get a fancy effect.
{codecitation html}<p><a class=”ost-transition ost-color ost-padding ost-border” href=”#”>Color – Padding – Border</a></p>{/codecitation}
You can see live examples of these transitions by clicking this demo below: