1. Using JavaScript
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, < span style> < span style = "color: RGB (0, 0, 0); color: RGB (0, 0, 0); overflow: hidden; } .box { box-sizing: border-box; width: 100px; height: 50px; line-height: 48px; font-size: 16px; text-align: center; border: 1px solid lightblue; background: lightcyan; } < / style > < body > < div class = "box" id = "box" > vertical center < / div > < / body > < script > = let HTML document. The documentElement, winW = HTML.clientWidth, winH = HTML.clientHeight, boxW = box.offsetWidth, boxH = box.offsetHeight; box.style.position = 'absolute'; box.style.left = (winW - boxW) / 2 + 'px'; box.style.top = (winH - boxH) / 2 + 'px'; </script> </html>Copy the code
======End======
2. The core is positioning (using CSS)
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, < span style> < span style = "color: RGB (0, 0, 0); color: RGB (0, 0, 0); overflow: hidden; } .box { box-sizing: border-box; width: 100px; height: 50px; line-height: 48px; font-size: 16px; text-align: center; border: 1px solid lightblue; background: lightcyan; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } < / style > < body > < div class = "box" id = "box" > vertical center < / div > < / body > < / HTML >Copy the code
======End======
The other one also uses positioning, but has limitations (the width and height of the box must be specified, not the percentage).
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, < span style> < span style = "color: RGB (0, 0, 0); color: RGB (0, 0, 0); overflow: hidden; } .box { box-sizing: border-box; width: 100px; height: 50px; line-height: 48px; font-size: 16px; text-align: center; border: 1px solid lightblue; background: lightcyan; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; } < / style > < body > < div class = "box" id = "box" > vertical center < / div > < / body > < / HTML >Copy the code
======End======
3. Use Flex (with browser compatibility issues), which is recommended if compatibility issues are not considered
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta http-equiv=" x-UA-compatible "content="ie=edge"> <title>Document</title>. 200px; height: 200px; border: 1px solid #6d7973; background-color: #2a2a2a; margin: 150px auto; display: flex; justify-content: center; align-items: center; } </style> </head> <body> <div class="box"></div> </body> </html>Copy the code
Ps: Hope to help!