Mobile Terminal layout: Write an adaptive square box, square box
Move side layout, div layout proportionally, width as a percentage, so that the height and width are the same, that is, make div A Square
Recently I was writing a small program and encountered a layout problem: a div width ratio width: 20%, for example, 20% of the screen width, to make the height and width the same, that is to say, how can we make this div A Square? Because the mobile terminal is used, the screen width is not fixed, and the div box is displayed as a square with the same width and height. The effect is as follows:
Now we will summarize the solutions we have found:
Solution 1: JavaScript/jQuery method:
<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>
Solution 2: Use padding-top or padding-bottom in CSS to support the box.
<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>
Solution 3: The unit of vw/h_is used, but note that the unit of vw/h_is to divide the width/height of the current view into 100 parts in average length, rather than the parent box, calculate all
<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>
Conclusion: The appearance of vw/VL makes it a better solution for screen adaptation to various widths, but it may not be supported on some models, all the time, you can choose your own needs!