html如何让div上下居中 css,前端面试CSS系列——DIV垂直水平居中

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

代码片段// HTML

绝对定位.parent{

position:relative;

}

// 第一种

.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%;

background: yellow;

transform: translate(-50px, -50px);

}

flex布局.parent {

width: 500px;

height: 500px;

background: pink;

display: flex;

align-items: center;

justify-content: center;

}

// 子元素可以固定宽高

.parent. child {

width: 100px;

height: 100px;

background: yellow;

}

// 子元素不设置宽高

.parent. child {

background: yellow;

}

table-cell.parent {

width: 500px;

height: 500px;

display: table-cell;

text-align: center;

vertical-align: middle;

background: pink;

}

.parent .child {

display: inline-table;

/*

// 这种写法也可以

display: inline-block;

display: inline; */

width: 100px;

height: 100px;

background: yellow;

}

Grid.parent {

width: 500px;

height: 500px;

display: grid;

background: pink;

}

.parent .child {

align-self: center;

justify-self: center;

width: 100px;

height: 100px;

background: yellow;

}

总结

让一个div垂直水平居中有两种情况,第一种是元素不固定宽高的,有三种方式使用绝对定位加transform偏移

使用flex布局,设置align-items:center;justify-content:center;

使用grid布局,设置align-self:center; justify-self:center;

如果元素有固定宽高,可以使用:绝对定位+transform偏移

绝对定位+负margin值

绝对定位+margin:auto

不固定宽高的三种方式

参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值