Two ways to implement square div using CSS

Two ways to implement square div using CSS

Goal: Create a square whose side length is equal to

Method 1: Use the unit vw, (ps I think this is the easiest method)

The html structure is also very simple, with only one div

<html>
<body>
    <div class="square">
   </div>
</body>
</html>
.square{
  width: 50vw;
  height: 50vw;
  background: blue;  
}

Method 2: Use padding-bottom

Key points:

1. height: 0, the content will overflow into the padding, don't worry~~

2. When the padding-bottom value is set as a percentage, it is relative to the width of the containing block.

3. Need to set the containing block

HTML structure:

<html>
<body>
    <div class="container">
       <div class="square">
       </div>
   </div>
</body>
</html>

css:

*{
        margin: 0;
    }
    /* Set to fill the visible area of ​​the page*/
    .container{
        height: 100vh; 
        width: 100vw;
        background: palegoldenrod;
    }
    .square{
        width: 50%; /* relative to the width of the container */
        padding-bottom: 50%; /* relative to container width */
        background: palegreen;
    }

That's it, two are enough. You can also use margin, but there will be a risk of collapse, so these two are enough~~

Summarize

The above are two methods that I introduced to you to use CSS to realize square div. I hope it will be helpful to you. If you have any questions, please leave me a message and I will reply to you in time!

<<:  Docker win ping fails container avoidance guide

>>:  Characteristics of JavaScript arrow functions and differences from ordinary functions

Recommend

Example analysis of mysql variable usage [system variables, user variables]

This article uses examples to illustrate the usag...

The scroll bar position is retained when scrolling the vant list component

The scroll bar position is retained when scrollin...

Refs and Ref Details in Vue3

The editor also shares with you the corresponding...

A solution to a bug in IE6 with jquery-multiselect

When using jquery-multiselect (a control that tra...

The latest MySQL 5.7.23 installation and configuration graphic tutorial

The detailed installation and configuration of th...

How to prevent users from copying web page content using pure CSS

Preface When I was typing my own personal blog, I...

CentOS 6-7 yum installation method of PHP (recommended)

1. Check the currently installed PHP packages yum...

Solve the problem of case sensitivity of Linux+Apache server URL

I encountered a problem today. When entering the ...

Steps to build MHA architecture deployment in MySQL

Table of contents MAH 1. Introduction to MAH Arch...

Detailed explanation of using Nginx reverse proxy to solve cross-domain problems

question In the previous article about cross-doma...

The difference between redundant and duplicate indexes in MySQL

MySQL allows you to create multiple indexes on a ...