外链论坛

 找回密码
 立即注册
搜索
查看: 69|回复: 1

前端面试CSS系列——DIV垂直水平居中

[复制链接]

2723

主题

119

回帖

9916万

积分

论坛元老

Rank: 8Rank: 8

积分
99160278
发表于 2024-6-30 05:41:33 | 显示全部楼层 |阅读模式

怎么让一个div 垂直水平居中

代码片段

// HTML <div class="parent"> <div class="child"></div> </div>

绝对定位

.parent{ position:relative; } // 第1种 .child{ position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); } // 第二种(必须固定宽高) .child{ position:absolute; width:100px; height:100px; top:50%; left:50%; margin-left:-50px; margin-top:-50px; } // 第三种(必须固定宽高) .child{ position:absolute; width:100px; height:100px; left:0; top:0; bottom:0; right:0; margin:auto; } // 第四中(固定宽高 + transform变形) .child{ position: absolute; width: 100px; height: 100px; left: 50%; top: 50%; bac公斤round: yellow; transform: translate(-50px, -50px); }

flex布局

.parent { width: 500px; height: 500px; bac公斤round: pink; display: flex; align-items: center; justify-content: center; } // 子元素能够固定宽高 .parent. child { width: 100px; height: 100px; bac公斤round: yellow; } // 子元素不设置宽高 .parent. child { bac公斤round: yellow; }

table-cell

.parent { width: 500px; height: 500px; display: table-cell; text-align: center; vertical-align: middle; bac公斤round: pink; } .parent .child { display: inline-table; /* // 这种写法能够 display: inline-block; display: inline; */ width: 100px; height: 100px; bac公斤round: yellow; }

Grid

.parent { width: 500px; height: 500px; display: grid; bac公斤round: pink; } .parent .child { align-self: center; justify-self: center; width: 100px; height: 100px; bac公斤round: yellow; }

Demo

总结

让一个div垂直水平居中有两种状况第1种是元素不固定宽高的,有三种方式

运用绝对定位加transform偏移运用flex布局,设置align-items:center;justify-content:center;运用grid布局,设置align-self:center; justify-self:center;

倘若元素有固定宽高,能够运用

绝对定位+transform偏移绝对定位+负margin值绝对定位+margin:auto不固定宽高的三种方式

参考

前端进阶

回复

使用道具 举报

0

主题

1万

回帖

1

积分

新手上路

Rank: 1

积分
1
发表于 2024-8-24 03:40:49 | 显示全部楼层
外链发布社区 http://www.fok120.com/
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

站点统计|Archiver|手机版|小黑屋|外链论坛 ( 非经营性网站 )|网站地图

GMT+8, 2024-10-5 13:37 , Processed in 0.066273 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2023, Tencent Cloud.