The small requirement of making a horizontally and vertically centered modal pop-up box should be common for front-ends like us.
Before CSS3 came out, there was only one way (that I could think of) to center elements both horizontally and vertically, which was to use js calculations to position them in the middle of the screen. This method is clumsy and troublesome.
The following two methods can quickly position elements to the middle of the screen.
flex layout
##
<style> .flex-mask { display: flex; position: fixed; z-index: 1; top: 0; left: 0; bottom: 0; right: 0; align-items: center; // 垂直居中 justify-content: center; // 水平居中 background: rgba(0,0,0,.5); } .flex-box { width: 500px; height: 300px; background-color: #fff; border-radius: 10px; } </style> <!-- 元素 --> <p class="flex-mask"> <p class="flex-box"></p> </p>
Use translate
<style> .transform-box { position: fixed; z-index: 2; top: 50%; left: 50%; width: 300px; height: 150px; background-color: red; border-radius: 10px; transform: translate(-50%, -50%); } </style> <p class="transform-box"></p>
The above is the detailed content of What are the two ways to set the horizontal and vertical centering of an element?. For more information, please follow other related articles on the PHP Chinese website!