ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 对元素垂直水平居中的几种处理方法 ![](https://box.kancloud.cn/3081f14a819db4bb998e46d26e4913ef_314x305.png) ~~~ <style> .parent{ width: 200px; height: 200px; background-color: green; } .child{ width: 100px; height: 100px; background-color: red; } </style> <div class="parent"> <div class="child"></div> </div> ~~~ ### 1.将父元素的display属性设为flex ~~~ /*css样式代码:*/ .parent{ display: flex; justify-content: center;/*该属性在flex、float布局里有详细说明*/ align-items: center;/*该属性在flex、float布局里有详细说明*/ } ~~~ ### 2.分别给父元素和子元素相对定位与绝对定位 #### 2.1利用top、left、margin属性进行调整 ~~~ /*css样式代码:*/ .parent{ position: relative; } .child{ position: absolute; top: 50%; left: 50%; margin-left: -50px; margin-top: -50px; } ~~~ #### 2.2利用top、left、transform属性进行调整 ~~~ /*css样式代码:*/ .parent{ position: relative; } .child{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); } ~~~ #### 2.3利用top、left、bottom、right属性进行调整 ~~~ /*css样式代码:*/ .parent{ position: relative; } .child{ position: absolute; margin: auto; top: 0; left: 0; bottom: 0; right: 0; } ~~~