如何使用 width: auto 转换内容的宽度? [英] How can I transition width of content with width: auto?

查看:25
本文介绍了如何使用 width: auto 转换内容的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元素,当它的内容改变时,我想为其宽度设置动画.它有 width: auto,并且永远不会改变.我已经看到了这个技巧,但那是为了在两个值之间转换并且一个值已经设置.我根本不操纵值,只操纵内容,并且我希望元素的大小随动画而变化.这在 CSS 中完全可行吗?

I have an element whose width I'd like to animate when its contents change. It has width: auto, and this never changes. I've seen this trick, but that's for transitioning between two values and one is set. I'm not manipulating the values at all, only the content, and I'd like my element's size to change with animation. Is this at all possible in CSS?

这是我的代码的简化版本:

Here's a simplified version of my code:

.myspan {
  background-color: #ddd;
}

.myspan:hover::after {
  content: "\00a0\f12a";
  font-family: Ionicons;
  font-size: 80%;
}

<link href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet"/>
<html>
  <body>
    <span class="myspan">Hello!</span>
  </body>
</html>

当用户将鼠标悬停在元素上时,我希望改变大小以动画化.

I'd like the changing size to animate when the user hovers over the element.

推荐答案

正如我所评论的,不能为 auto 设置动画(目前),所以要么使用 max-width/max-height 技巧,或者,如果您需要更精确,请使用脚本设置宽度.

As I commented, one can't animate auto (yet), so either use the max-width/max-height trick, or, if you need it to be more exact, set the width using a script.

使用 max-width/max-height 技巧,给它一个足够大的值以容纳最宽的.

With the max-width/max-height trick, give it a value big enough to accommodate the widest.

堆栈片段

.myspan {
  display: inline-block;
  font-size: 30px;
  background-color: #ddd;
  vertical-align: bottom;
}
.myspan::after {
  content: " \00a0\f12a ";
  font-family: ionicons;
  font-size: 80%;  
  display: inline-block;
  max-width: 0;
  transition: max-width .6s;
  vertical-align: bottom;
  overflow: hidden;
}
.myspan:hover::after {
  max-width: 80px;
  transition: max-width 1s;
}

<link href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" />

<span class="myspan">Hello!</span>

这篇关于如何使用 width: auto 转换内容的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆