You can set either the horizontal or vertical center mode of the element or the center mode.
It should be common for our front-ends to create a small horizontal and vertical modal bullet box.
Before css3 came out, there was only one way (I can think of) for elements to be horizontally centered and vertically centered, that is, to locate them in the center of the screen through js computing. This method is stupid and troublesome.
The following two methods allow elements to be quickly located in the middle of the screen.
Flex Layout
1 <style> 2. flex-mask {3 display: flex; 4 position: fixed; 5 z-index: 1; 6 top: 0; 7 left: 0; 8 bottom: 0; 9 right: 0; 10 align-items: center; // vertical center 11 justify-content: center; // horizontal center 12 background: rgba (0, 0 ,. 5); 13} 14. flex-box {15 width: 500px; 16 height: 300px; 17 background-color: # fff; 18 border-radius: 10px; 19} 20 </style> 21 22 <! -- Element --> 23 <div class = "flex-mask"> 24 <div class = "flex-box"> </div> 25 </div>
Use translate
1 <style> 2 .transform-box { 3 position: fixed; 4 z-index: 2; 5 top: 50%; 6 left: 50%; 7 width: 300px; 8 height: 150px; 9 background-color: red;10 border-radius: 10px;11 transform: translate(-50%, -50%);12 }13 </style>14 15 <div class="transform-box"></div>