用户3836409
几种水平垂直居中的方法
原创
关注作者
前往小程序,Get
更优
阅读体验!
立即前往
腾讯云
开发者社区
文档
建议反馈
控制台
登录/注册
首页
学习
活动
专区
工具
TVP
最新优惠活动
文章/答案/技术大牛
搜索
搜索
关闭
发布
首页
学习
活动
专区
工具
TVP
最新优惠活动
返回腾讯云官网
用户3836409
首页
学习
活动
专区
工具
TVP
最新优惠活动
返回腾讯云官网
社区首页
>
专栏
>
几种水平垂直居中的方法
几种水平垂直居中的方法
原创
用户3836409
关注
修改于 2018-11-19 10:56:55
690
0
修改于 2018-11-19 10:56:55
举报
文章被收录于专栏:
Sublime
前言
最近刷前端面试题经常看到CSS水平垂直居中设置的标题,找了下相关办法试了下,总结了一些比较常用的。 这儿一致设置父元素和定位子元素为 .box{ width: 400px; height: 400px; background: #cae;}#content { width: 300px;height: 300px; background: #fc1;}(一)position办法 设置父元素相对定位,子元素肯定定位,使用子元素的肯定定位使子元素水平垂直居中,这种办法要知道元素的巨细; .box { width: 400px; height: 400px; background: #cae; position: relative; }#content { width: 300px;height: 300px; background: #fc1; position: absolute; top: 50px;left: 50px; }(二)position+margin办法 1.父元素相对定位,子元素肯定定位距离都设置为0,使用margin:auto;使子元素水平垂直居中. .box2 { width: 400px; height: 400px; background: #f1f; position: relative; }#content2 { width: 300px;height: 300px; margin:auto; background: #fc1; position: absolute; top: 0;left:0;bottom: 0;right: 0; }2.1.父元素相对定位,子元素肯定定位距离设置为50%(这儿50%应该是父元素巨细的50%),经过设置子元素巨细的一半的负margin值使子元素水平垂直居中. .box3{ width: 400px; height: 400px; background: #23f; position: relative; }#content3 { width: 300px;height: 300px; background: #fc1; position: absolute; top: 50%;left: 50%; margin-top: -150px; margin-left: -150px; }(三)table-cell 办法 .box4{ width: 400px; height: 400px; background: #456; display: table-cell; text-align: center; vertical-align: middle; }#content4 { width: 300px;height: 300px; background: #fc1; display: inline-block; }(四)position+transform 办法 .box5{ width: 400px; height: 400px; background: #789; position: relative; }#content5 { width: 300px;height: 300px; margin:auto; background: #fc1; position: absolute; top: 50%;left: 50%; -webkit-transform:translate(-50%,-50%); transform:translate(-50%,-50%); }(五)flex 办法 1.使用弹性布局flex:设置align-items,justify-content都为center; .box6{ width: 400px; height: 400px; background: #1f1; display: flex; align-items:center; justify-content:center; }#content6 { width: 300px;height: 300px; background: #fc1; }2.弹性布局,子元素margin设置auto即可. .box7{ width: 400px; height: 400px; background: #aaf; display: flex; }#content7 { width: 300px;height: 300px; background: #fc1; margin:auto; }
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系
cloudcommunity@tencent.com
删除。
其他
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系
cloudcommunity@tencent.com
删除。
其他
评论
登录
后参与评论
0 条评论
热度
最新
推荐阅读
LV.
文章
0
获赞
0
领券
问题归档
专栏文章
快讯文章归档
关键词归档
开发者手册归档
开发者手册 Section 归档
0
0
0
推荐