目标
遇到一个需求,让图片在页面中,不管宽度如何变化(各种尺寸的手机屏幕下),宽高保持16:9的比例。
实现
方法一:这也是比较经典的一个方法,利用padding-bottom来实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| <!DOCTYPE html> <html> <head> <title>固定宽高比16:9</title> <style type="text/css"> *{ margin: 0px; padding: 0px; } .wrap{ width:100%; } .box{ width: 100vw; height: 0px; position: relative; padding-bottom: 56.25%; background: pink; }
</style> </head> <body> <div class="wrap"> <div class="box"> <p>这是一个16:9的矩形</p> </div> </div> </body> </html>
|
方法二:利用vmin来实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| <!DOCTYPE html> <html> <head> <title>固定宽高比16:9</title> <style type="text/css"> *{ margin: 0px; padding: 0px; } .wrap{ width:100%; } .box{ height: 56.25vmin; background: pink; }
</style> </head> <body> <div class="wrap"> <div class="box"> <p>这是一个16:9的矩形</p> </div> </div> </body> </html>
|
注意:如果屏幕宽度较大高度较小时,则可以用vmax。如果需要随意切换时,可以通过js来控制。
总结
两种方法各有利弊,方法一:兼容性好,代码相对长点,理解也比较困难点。方法二:代码简洁,理清定义后便非常容易理解,但是兼容性相对差一些。不过兼容性啥的,怕什么哈哈哈。