css horizontal and vertical centering

The first given structure is as follows: 

  <div class="red-box">
    <div class="blue-box"></div>
  </div>

 

method 1: 

      .red-box {
            position: relative;
            width: 500px;
            height: 300px;
            border: 1px solid red;
        }
        
        .blue-box {
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            
            margin: auto;

            width: 300px;
            height: 200px;
            border: 1px solid blue;
        }

This method should pay attention to 3 points:

  1. The value of the top, right, bottom, and left of absolute positioning is 0 (in fact, a specific value can be set, and the specific effect can be tried by yourself)

    This step will make the child element fill the parent element

  2. Set the width and height of the element, which cannot be larger than the parent element

 

  3. Set margin: auto; this is to allocate the remaining space of the parent element to achieve centering

 

  

 

Method 2: 

This method is to use the new features of css3 to achieve centering:

translate is based on the width and height of the element itself

        .red-box {
            position: relative;
            width: 500px;
            height: 300px;
            border: 1px solid red;
        }

        .blue-box {
            position: absolute;
            top: 50%;
            left: 50%;

            transform: translate(-50%,-50%);
            
            border: 1px solid blue;
        }

 

 

 

 

Method 3:

Centering using css3 flex layout

        .red-box {
            display: flex;
            align-items: center;
            justify-content: center;

            width: 500px;
            height: 300px;
            border: 1px solid red;
        }

        .blue-box {
            border: 1px solid blue;
        }

 

 

The above are the centering methods that I often use, and here is just a brief summary.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324966677&siteId=291194637