I was writing a small program recently and encountered a layout problem: the width ratio of a div is width: 20%, for example, 20% of the screen width. I want the height to be the same as the width, that is, to make the div a square. How to achieve this? Because we are working on a mobile terminal, the screen width is variable, and we want the div box to be the same width and height and appear as a square. The effect is as follows:
Now let’s summarize the solutions found:
Option 1: JavaScript/jQuery method:
<code> <style> *{ margin: 0; padding: 0; } html,body{ width: 100%; height: 100%; } ul{ width: 100%; list-style: none; } li{ width: 20%; float: left; } li:first-child{ background: red; } li:nth-child(2){ background: green; } li:nth-child(3){ background: blue; } li:nth-child(4){ background: yellow; } li:nth-child(5){ background: pink; } </style> </head> <body> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> <script src="wjs/lib/jquery/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(window).on('resize', function () { $('li').css('height',$('li').css('width')); }).trigger('resize'); }) </script> </code>
Option 2: Prop up the box through padding-top or padding-bottom in CSS
<code><style> *{ margin: 0; padding: 0; } html,body{ width: 100%; height: 100%; } ul{ width: 100%; list-style: none; } li{ width: 20%; float: left; padding-top: 20%; } li:first-child{ background: red; } li:nth-child(2){ background: green; } li:nth-child(3){ background: blue; } li:nth-child(4){ background: yellow; } li:nth-child(5){ background: pink; } </style> </head> <body> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </code>
Option 3: Use the vw/vh unit, but it should be noted that the vw/vh unit divides the width/height of the current viewport into 100 equal lengths, not the parent box, so all needs to be calculated
<code><style> *{ margin: 0; padding: 0; } html,body{ width: 100%; height: 100%; } ul{ width: 80%; margin: 0 auto; list-style: none; } li{ width: 16vw; height: 16vw; float: left; } li:first-child{ background: red; } li:nth-child(2){ background: green; } li:nth-child(3){ background: blue; } li:nth-child(4){ background: yellow; } li:nth-child(5){ background: pink; } </style> </head> <body> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </body> </code>
Summary: The emergence of vw/vh units undoubtedly provides a better solution for adapting to screens of various widths, but it may not be supported on some models, so sometimes it is better to use each one according to your needs!