current position:Home>CSS realizes the square of adaptive screen width

CSS realizes the square of adaptive screen width

2022-04-29 08:11:49A programmer who can only write bugs

Ideas , Square , The length and width are the same , You need to find a standard value and then set the box model , It can be used padding,margin, width/height,
Begin with topic
1. Use padding, reason , The percentage is based on the width of the parent element , So if it's based on the percentage of the parent box , You can use this method  Insert picture description here
The specific code is as follows

<div class="square"></div>
.square {
    
    display: inline-block;
    padding: 0 20% 20% 0;
    background: red;
}
  1. padding+flex, Suitable for making multiple squares , Using the same padding Open the box model , Make the height the same as the width
<div class="square-wrapper">
    <div class="square"></div>
    <div class="square"></div>
</div>
.square-wrapper {
    
    display: flex;
}
.square {
    
    flex: 1;
}
.square::after {
    
    content: "";
    display: block;
    padding-bottom: 100%;
    background: #000;
}
  1. The same principle can also be used to add... To internal elements margin To finish opening the box
.square-wrapper {
    
    display: flex;
}
.square {
    
    flex: 1;
    background: #000;
}
.square::after {
    
    content: "";
    display: block;
    margin-bottom: 100%;
}
  1. rem / em It's all the same value ,rem What you get is html Labeled font-size,em It's the parent element font-size, It is also fixed
  2. Use vw, Indicates that the width of the screen is cut into 100 Share , Then you can perfectly adapt to all kinds of screens ( The screen here refers to including this document Object's container , If it opens in the browser , Then it is the width that can be displayed inside the browser ; If in iframe Open in , Namely iframe Width )
.square {
    
    width: 20vw;
    background: #000;
}
.square::after {
    
    content: "";
    display: block;
    padding-bottom: 100%;
    // margin-bottom: 100%; //  It's fine too 
}

For the moment, I think of so much . If you have a better one , You can leave a message and tell me ~

copyright notice
author[A programmer who can only write bugs],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290558476195.html

Random recommended