如何為不定高度(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 值進行過渡效果,所以最好不要大得離譜,否則動畫效果不理想。

 

 1 <!DOCTYPE html>
 2 <html lang="en">
 3     <head>
 4         <meta charset="utf-8">
 5         <style>
 6             *{
 7                 margin: 0;
 8                 padding:0;
 9             }
10             div{
11                 
12                 display: inline-block;
13                 overflow: hidden;
14                 background-color: orange;
15                 max-height: 20px;
16                 -webkit-transition: max-height 1s;
17                 transition: max-height 1s;
18             }
19             div:hover{
20                 max-height:200px;
21             }
22         </style>
23     </head>
24     <body>
25         <div>
26             <p>我不是height,是max-height</p>
27             <p>我不是height,是max-height</p>
28             <p>我不是height,是max-height</p>
29             <p>我不是height,是max-height</p>
30             <p>我不是height,是max-height</p>
31             <p>我不是height,是max-height</p>
32         </div>
33     </body>
34 </html>

 

參考資源:http://stackoverflow.com/questions/3508605/css-transition-height-0-to-height-auto

這是我第一篇博客文章,希望能讓大家學到東西。當然,我更希望收到大家對我的建議!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM