Briefly describe 3 methods of horizontal and vertical centering layout

I just thought about it when I encountered a classic interview question.

This question is relatively simple, but it is not so easy to think through various angles. In fact, the various methods are similar.

 

basic structure:

<body>
    <div id="con">
        <div id="back" class="center">
        </div>
    </div>

</body>

 

1. Use absolute positioning to set the top, left, and margin attributes.

#back {
   position: absolute;
   width: 300px;
   height: 300px;
   background-color: gray;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}

2. Use absolute positioning to set the top right bottom left property.

#back {
   position: absolute;
   width: 300px;
   height: 300px;
   border: 1px solid red;
   top: 0;
   left: 0;
   bottom: 0;
   right: 0;
   margin: auto;
}

3. Use flex layout

#con {
   display: flex;
   justify-content: center;
   align-items: center;
   height: 800px;
}

#back {
   width: 300px;
   height: 300px;
   border: 1px solid purple;
}

In fact, these basic usages are rarely used in engineering projects, and they all rely on frameworks. However, the basic principles still need to be known. Explore other ways on your own.

Life has a limit but knowledge not.

Guess you like

Origin blog.csdn.net/vampire10086/article/details/108256147