I'm having a bit of a problem making script-less CSS-only animated transition of an element that's initially set to a fixed width and should expand on mouse over to auto width according to content in it. When mouse goes out it should collapse back to fixed width.
Let's say I have a menu:
<menu>
<li>Item</li>
<li>Item with long text</li>
</menu>
Initially it would display as a collapsed 50px wide vertical bar with icons only. When one mouses over it reveals icon labels.
This is a simplified example of what I'm trying to achieve. First menu is the one that needs to transition and second one is there just to show what auto width should be for this amount of content.
Problem
This is just part of the whole CSS that plays an important role here:
menu {
width: 50px;
}
menu:hover {
width: auto; /* setting to other fixed width works as expected */
}
The problem is that when you set width to auto one of the two will happen:
- Browser animates from fixed width 0 (Chrome) - if we then add
min-widthit does next one - Browser doesn't animate anything just applies new style
You can make use of the max-width trick, it's not perfect, but it gets around the problems with transitioning a numeric value to a string state:
(the above has been updated with float:left)
The downside to this method is that you have to set a max width for your menu, but then I usually find that this is a good thing to do anyway.
markup:
<div class="menu">
<a href="#">[i] Hello</a>
<a href="#">[i] There</a>
</div>
css:
div a {
display: block;
overflow: hidden;
white-space: nowrap;
}
.menu {
transition: all 2s;
max-width: 17px;
/*
here you can set float:left or position:absolute
which will force the menu to collapse to it's minimum
width which, when expanded, will be the actual menu
item widths and not max-width.
*/
float: left;
}
.menu:hover {
/*
If you have the possibility of varied widths, i.e. multilingual
then make sure you use a max-width that works for them all. Either
that or do what a number of multilingual sites do and set a body
class that states the current language, from there you can then
tailor your max-width differently e.g. wider for German.
*/
max-width: 300px;
}
Example of seperate dimensions for multilingual:
.lang-de .menu:hover { max-width: 400px; }
.lang-gb .menu:hover { max-width: 300px; }
So instead of transitioning the width, you are actually modifying the max-width property, which you can set a fixed value to more easily, all because it will only come into use when this limit has been reached, and remains invisible until then.
来源:https://stackoverflow.com/questions/17549282/width-transitioning-from-fixed-size-to-auto-using-css-without-javascript