It's been a while since I worked with stylesheets. I have always been a software developer focused mostly on backend functionality. Recently, however, I started using the Bear blogging platform for my personal website, which allows you to customize its built-in themes.
The menu of my website is a collection of icons that link to different pages. For example, ✍️ points to a page with an overview of all my blog posts. My goal for this and other menu icons was to animate them on hover, so they scale up.
A Simple Solution
In its basic form, the HTML of the menu looks like this:
<nav>
<a href="/blog/">✍️</a>
<a href="/music/">🎼</a>
</nav>
Of course, I could do something simple (and probably not very professional) in CSS like this:
nav a {
text-decoration: none;
}
nav a:hover {
font-size: 1.5em;
}
Check out this example in CodePen:
This works, but it's far from ideal:
- There is no animated transition; a menu item immediately grows in size on hover and shrinks back on unhover.
- Surrounding menu items move around on hover.
Working with Transitions
A better way to create good-looking animations for your menu is by using transition
. With a transition, you can define which properties of an element will be animated. This transition
property is placed on the main element (not on the :hover
selector). Then, on the :hover
selector, you can use the transform
property to define the type of animation on hover.
In my case, the stylesheet looks like this:
nav a {
display: inline-block;
text-decoration: none;
transition: transform .3s ease-in-out;
}
nav a:hover {
transform: scale(1.5);
}
I'll explain each part below:
- The transition animation only works for block elements, not for inline elements. So, I need to ensure that the CSS handles my
a
tags as blocks withdisplay: inline-block
. -
transition: transform .3s ease-in-out
means that atransition
is applied to thetransform
property, the animation takes.3
seconds, and the animation is triggered both on hover and unhover. -
transform: scale(1.5)
defines the type of transition. In this case, it scales my menu icons by a factor of1.5
.
Check out this example in CodePen:
For more options and transformation effects, check out the documentation for the transition property and the transform property.