如何為不定高度(height:auto)的元素添加CSS3 transition-property:height 動畫,

來源:互聯網
上載者:User

如何為不定高度(height:auto)的元素添加CSS3 transition-property:height 動畫,

但一個元素不設定height時,它的預設值是 auto,瀏覽器會計算出實際的高度。

但如果想給一個 height:auto 的區塊層級元素的高度添加 CSS3 動畫時,該怎麼辦呢?

從 MDN 的可以查到 CSS 支援動畫的屬性中的 height 屬性如下:

height :yes, as a length, percentage 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

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.