700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 让一个 div 水平垂直居中的几种方法

让一个 div 水平垂直居中的几种方法

时间:2020-05-24 01:12:48

相关推荐

让一个 div 水平垂直居中的几种方法

水平垂直居中有好多种实现方式,主要就分为两类:不定宽高定宽高,以在body下插入一个div为例:

定宽高 使用定位+margin

element.style {position: absolute;left: 50%;top: 50%;margin-left: -250px;margin-top: -250px;width: 500px;height: 500px;background: yellow;z-index: 1;}

使用定位+transfrom

element.style {position: absolute;left: 50%;top: 50%;width: 500px;height: 500px;background: yellow;z-index: 1;transform: translate3d(-50%,-50%,0);}

table-cell 方式

div.parent-box {display: table;width: 100%;}div.parent {display: table-cell;height: 200px;width: 200px;background-color: orange;text-align: center;vertical-align: middle;}div.child {display: inline-block;width: 100px;height: 100px;background-color: blue;}

<div class="parent-fix"><div class="parent"><div class="child">DEMO</div></div></div>

table-cell 是不支持设置 width: 100%; 想让 .parent 和 其容器宽度一致最好设置一个 dispaly: table; 父容器。calc方式

.parent {border: 1px solid;width: 1000px;height: 1000px;}.child {position: relative;border: 1px solid;width: 100px;height: 100px;top: calc(50% - 50px);left: calc(50% - 50px);}

不定宽高:不定宽高的方法基本都适用于定宽高的情况,这里把div的宽高按照内容展开,使用定位+transform同样是适用的

div.parent {position: reletive;}element.style {position: absolute;left: 50%;top: 50%;background: yellow;z-index: 1;transform: translate3d(-50%,-50%,0);}

flex、grid方法:

div.parent{display:flex;}div.child{margin:auto;}

// 子元素自动垂直水平居中div.parent {display: flex;justify-content: center;align-items: center;}

或者

div.parent{display:flex;}div.child{margin:auto;}

static 方法

div.parent {font-size: 0;text-align: center;&::before {content: "";display: inline-block;width: 0;height: 100%;vertical-align: middle;}}div.child{display: inline-block;vertical-align: middle;}

此法来自张鑫旭的《CSS世界》,原理就是:设置inline-blockvertical-align:middle后,里面的元素会基于中间的文字准线居中对齐(学生时代的英语本子里面写字母,都是4条线形成三个空白区域,文字的对齐就是根据这几条线的)vertical-align更多信息可以看看张鑫旭博文; 然后,由于伪类是position:static(默认)的,那么伪类撑开了父元素的基准线(高度是100%),使得此时文字的基准线就是整个div.parent的中心了,另外vertical-align只影响inline或者inline-block的,所以div.child设置vertical-align就能居中了。

参考资料:/question/css/52.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。