如何为不定高度(height:auto)的元素添加CSS3 transition-property:height 动画

38 篇文章 0 订阅

转自:如何为不定高度(height:auto)的元素添加CSS3 transition-property:height 动画


当一个元素不设置height时,它的默认值是 auto,浏览器会计算出实际的高度。

但如果想给一个 height:auto 的块级元素的高度添加 CSS3 动画时,该怎么办呢?

从 MDN 的可以查到 CSS 支持动画的属性中的 height 属性如下:

height :yes, as a lengthpercentage or calc(); // 当 height 的值是 length,百分比或 calc() 时支持 CSS3 过渡。

所以当元素 height : auto 时,是不支持 CSS3 动画的。

除了通过 JS 获取精确的 height 值的方法外,其实我们可以使用 max-height 代替 height

只要我们设置一个肯定比元素自增长大的高度值就可以了。当然,因为是根据 max-height 值进行过渡效果,所以最好不要大得离谱,否则动画效果不理想。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <style>
            *{
                margin: 0;
                padding:0;
            }
            div{
                
                display: inline-block;
                overflow: hidden;
                background-color: orange;
                max-height: 20px;
                -webkit-transition: max-height 1s;
                transition: max-height 1s;
            }
            div:hover{
                max-height:200px;
            }
        </style>
    </head>
    <body>
        <div>
            <p>我不是height,是max-height</p>
            <p>我不是height,是max-height</p>
            <p>我不是height,是max-height</p>
            <p>我不是height,是max-height</p>
            <p>我不是height,是max-height</p>
            <p>我不是height,是max-height</p>
        </div>
    </body>
</html>

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,需要将 `position` 属性的拼写更正为 `position`。其次,如果要实现底部对齐,需要将父元素 `#container` 的高度设置为 100%,并将其位置设置为相对定位 `position: relative`。然后,在子元素 `.login_fields__submit` 中设置 `align-self: flex-end`,使其垂直对齐到父元素的底部。最后,需要将子元素 `.login_fields__submit` 的位置设置为绝对定位 `position: absolute`,并且设置 `left: 0; bottom: 0;`,使其固定在父元素的底部。 以下是修改后的 CSS 代码: ``` #container { width: 500px; background-color: #fff; height: 550px; margin: 2% auto; border-radius: 10px; box-shadow: 0 0 0 5px deepskyblue, 0 0 0 10px orangered, 0 0 0 15px deepskyblue; position: relative; /* 修改为相对定位 */ height: 100%; /* 设置高度为100% */ } .login_fields__submit { display: flex; justify-content: flex-end; align-items: flex-end; align-self: flex-end; /* 添加这行代码,使其垂直对齐到父元素的底部 */ position: absolute; /* 修改为绝对定位 */ left: 0; /* 设置为0 */ bottom: 0; /* 设置为0 */ } .login_fields__submit input { margin-top: auto; border-radius: 50px; background: transparent; padding: 10px 0px; border: 2px solid #4FA1D9; color: #4FA1D9; text-transform: uppercase; font-size: 14px; width: 22%; -webkit-transition-property: background, color; transition-property: background, color; -webkit-transition-duration: 0.2s; transition-duration: 0.2s; margin-right: 19%; position: relative; } ``` 这样,就可以实现底部对齐了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值