高度的 CSS 过渡而不设置静态初始高度

Posted

技术标签:

【中文标题】高度的 CSS 过渡而不设置静态初始高度【英文标题】:CSS transition for height without setting a static initial height 【发布时间】:2022-01-23 20:25:36 【问题描述】:

我正在尝试应用一个类,该类将使用 CSS 过渡将不透明度和高度从默认的 100% 均匀地淡化为 0。

发生的情况是不透明度均匀衰减,但高度保持在 100%,然后在 0.5 秒过渡结束时跳到 0。

如何让高度与不透明度一起均匀过渡?

更新: 如果不在 div 上设置静态初始高度,如何做到这一点?文本流向的高度在不同的浏览器宽度下会有所不同。

function fadeOut()
$('#intro').addClass('fadeout');


$('#fadeout').on('click', fadeOut);
.fullheight
  position: relative;
  height: 100%;


.fadeout
  opacity: 0;
  height: 0;
  transition: all .5s;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fullheight" id="intro">Here is some long intro text that we will fade out. Here is some long intro text that we will fade out. Here is some long intro text that we will fade out. Here is some long intro text that we will fade out. Here is some long intro text that we will fade out. Here is some long intro text that we will fade out. Here is some long intro text that we will fade out. Here is some long intro text that we will fade out.</div>
<button id="fadeout">Fade out</button>

【问题讨论】:

【参考方案1】:

为此,您需要在我的示例中将高度设置为 100px 之类的设定值

function fadeOut()
$('#intro').addClass('fadeout');


$('#fadeout').on('click', fadeOut);
.fullheight
  position: relative;
  height: 100px;


.fadeout
  opacity: 0;
  height: 0;
  transition: all .5s;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fullheight" id="intro">Here is some long intro text that we will fade out. Here is some long intro text that we will fade out. Here is some long intro text that we will fade out. Here is some long intro text that we will fade out. Here is some long intro text that we will fade out. Here is some long intro text that we will fade out. Here is some long intro text that we will fade out. Here is some long intro text that we will fade out.</div>
<button id="fadeout">Fade out</button>

【讨论】:

谢谢。但是,如果不在 div 上设置静态初始高度,如何做到这一点?文本将在不同的浏览器宽度下流动到不同的高度,所以我不想将它限制在一个初始高度。

以上是关于高度的 CSS 过渡而不设置静态初始高度的主要内容,如果未能解决你的问题,请参考以下文章

div中心的CSS过渡宽度和高度

子高度变化时包装器 div 的过渡高度

图像上的 CSS 过渡不起作用

css3高度过渡不起作用

高度自适应不能触发transition的解决方法

Css过渡高度使用javascript不起作用[重复]