ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
1. 给元素绝对定位后,translate(-50%, -50%) ```css img { /* --居中-- */ position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); } ``` 2. 父元素相对定位,子元素绝对定位,top, bottom, left, right 以及 margin都设置为0 ```css .parent { position: relative; } .child { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; } ``` 3. flex 布局方法,将父元素,display改为flex,align-item,和 justify-content设置为center ``` .parent { width: 200px; height: 200px; background-color: pink; display: flex; /\* 当 flex 横向排列时,align-item 指的是垂直方向 \*/ align-items: center; /\* 当 flex 横向排列时,justify-content 指的是横向方向 \*/ justify-content: center; } .son { width: 100px; height: 100px; background-color: cadetblue; } ``` 4. gird 布局 ``` .parent { display: grid; align-item: center; justify-item: center; } ``` 5. table 布局 ``` .parent { display: table-cell; vertical-align: middle; vertical-align: center; } ```