Maison  >  Article  >  interface Web  >  如何为什么不定高度的元素添加CSS3 transition_html/css_WEB-ITnose

如何为什么不定高度的元素添加CSS3 transition_html/css_WEB-ITnose

WBOY
WBOYoriginal
2016-06-24 11:42:231402parcourir

但一个元素不设置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>

 

这是我第一篇博客文章,希望能让大家学到东西。当然,我更希望收到大家对我的建议!

 

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn