Open
Description
<div class="parent">
<div class="child"></div>
</div>
div.parent {
display: flex;
justify-content: center;
align-items: center;
}
div.parent {
position: relative;
}
div.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* 或者 */
div.child {
width: 50px;
height: 10px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -25px;
margin-top: -5px;
}
/* 或 */
div.child {
width: 50px;
height: 10px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
div.parent {
display: grid;
}
div.child {
justify-self: center;
align-self: center;
}
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;
}
Activity
Feather130 commentedon Apr 11, 2019
楼上总结的差不多了。再加一种
cleverboy32 commentedon Apr 11, 2019
mengsixing commentedon Apr 11, 2019
补充一个,使用 table-cell 的方式:
Moriarty02 commentedon Apr 11, 2019
水平垂直居中有好多种实现方式,主要就分为两类不定宽高和定宽高
以在body下插入一个div为例
使用定位+margin
使用定位+transfrom
不定宽高的方法基本都适用于定宽高的情况
这里把div的宽高按照内容展开
使用定位+transform同样是适用的
还有一些其他的方法比如使用父容器使用flex,grid,table
这两个楼上也提到了,是可以实现的,但是在实际应用中,
因为改变了父容器的display,在多个子节点反而不好用了
cb3570594 commentedon Apr 11, 2019
同理:
div.parent{ display:grid; } div.child{ margin:auto; }
zeroone001 commentedon Apr 11, 2019
需要再补充一个@cleverboy32
sohoorc commentedon Apr 11, 2019
hjskevin commentedon Apr 11, 2019
我总结的方法:https://juejin.im/post/5ca1a585f265da30dc7ac3f7
yiqingfeng commentedon Apr 11, 2019
table-cell 是不支持设置 width: 100%; 想让
.parent
和 其容器宽度一致最好设置一个dispaly: table;
父容器。cleverboy32 commentedon Apr 12, 2019
@zeroone001 在 parent 有宽高的时候, child 已经垂直居中了
zeroone001 commentedon Apr 13, 2019
不行
display: table-cell; 这个居中不了,必须要第三个元素在child里面
XinChou16 commentedon Apr 15, 2019
100%高度的 after 加上 inline-block
Caitingwei commentedon Apr 20, 2019
huijingL commentedon Apr 21, 2019
楼上大神们指出的很全了,
我指出一点:
使用 margin-left 和 margin-top, 相对的是父元素,
transform: translate 相对的自身,
这是他们的一点区别,实际上我是想问一下,他们还有没有其他的区别 ,望后续大神指出;
前端小白,有错勿怪,感谢指正
16 remaining items