我在对元素进行无脚本的纯CSS动画过渡时遇到了一个问题,该元素最初设置为固定宽度,并应根据其内容在鼠标上扩展为自动宽度。当鼠标熄灭时,它应该折叠回固定宽度。
假设我有一个菜单:
<menu>
<li>Item</li>
<li>Item with long text</li>
</menu>
最初,它会显示为折叠的50px宽的垂直栏,仅带有图标。当鼠标悬停在其上时,将显示图标标签。
我要实现的目标的This is a simplified example。第一个菜单是需要转换的菜单,第二个菜单只是为了显示此内容量应具有的自动宽度。
问题
这只是整个CSS的一部分,在这里起着重要的作用:
menu {
width: 50px;
}
menu:hover {
width: auto; /* setting to other fixed width works as expected */
}
问题是,当您将
width
设置为auto
时,将发生以下两种情况之一:浏览器从固定宽度0(Chrome)开始设置动画-如果我们随后添加
min-width
,则会执行下一个动画浏览器不设置任何动画,仅应用新样式
最佳答案
您可以利用max-width
技巧,它并不完美,但是可以解决将数字值转换为字符串状态的问题:
http://jsfiddle.net/Cqmuf/1/
(以上内容已用float:left
更新)
这种方法的缺点是您必须为菜单设置最大宽度,但是我通常会发现这样做还是一件好事。
标记:
<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;
}
多语言的单独尺寸示例:
.lang-de .menu:hover { max-width: 400px; }
.lang-gb .menu:hover { max-width: 300px; }
因此,您实际上不是在修改宽度,而是在修改
max-width
属性,可以更轻松地将其设置为固定值,这都是因为只有在达到此限制时才使用该属性,并且在此之前保持不可见。关于css - 使用没有Javascript的CSS将宽度从固定大小转换为“自动”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17549282/