演示地址:点我
1、完美居中:绝对定位 + transform,适用于元素宽高未知的大多数情况
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> .parent { position: relative; height: 300px; width: 300px; background: #ddd;; } .child { position: absolute; height: 100px; width: 100px; left: 50%; top: 50%; transform: translate(-50%, -50%); background: #333; } </style></head><body> <div class="parent"> <div class="child"></div> </div></body></html>2、完美居中:flex布局,需要兼容flex
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> .parent { display: flex; justify-content: center; align-items: center; height: 300px; width: 300px; background: #ddd; } .child { height: 100px; width: 100px; background: #333; } </style></head><body> <div class="parent"> <div class="child"></div> </div></body></html>3、内联元素水平居中:text-align,适用于常规文档流中的内联元素(span、a、input等),也包括inline-block元素
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> .parent { text-align: center; height: 300px; width: 300px; background: #ddd; } .child { height: 50px; width: 100px; background: #aaa; } </style></head><body> <div class="parent"> <span class="child">span</span><br> <input type="text" class="child" value="input"><br> <div class="child" style="display: inline-block;">inline-block</div><br> </div></body></html>新闻热点
疑难解答