css - 使用没有 Javascript 的 CSS 将宽度从固定大小转换为 "auto"

标签 css width css-transitions

我在制作一个元素的无脚本纯 CSS 动画过渡时遇到了一些问题,该元素最初设置为固定宽度并且应该根据其中的内容在鼠标悬停时扩展到自动宽度。当鼠标离开时,它应该折叠回固定宽度。

假设我有一个菜单:

<menu>
    <li>Item</li>
    <li>Item with long text</li>
</menu>

最初它会显示为一个折叠的 50 像素宽的垂直条,只有图标。当鼠标悬停在上面时会显示图标标签。

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 将宽度从固定大小转换为 "auto",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17549282/

相关文章:

javascript - 使用 5-star CSS 解决方案,当屏幕在 330px 线下换行时无法点击第二行

jquery - 当我们点击后面时,前面应该在点击事件中打开

html - CSS - 响应图像大小

css - 使用 CSS 时 Canvas 被拉伸(stretch),但具有 `width` 和 `height` 属性时正常

css - Chrome 中的不透明度转换无法获得 60fps

jquery - 需要可扩展的多个开/关按钮

javascript - 获取 div 宽度并添加到边框

html - 我有 2 列 <div> 并且宽度相互挤压

css - 使用 css 3 矩阵旋转超过 360 度

css - 元素在 Safari、Chrome 和 FF 中获得蓝色背景是可以的