目录
<div class="parent">
<div class="child"></div>
</div>
1、div 宽高已知—进行水平垂直居中
(1)子绝父相 与 负边距实现
.parent {
position: relative;
width: 600px;
height: 600px;
}
.child {
position: absolute;
width: 100px;
height: 100px;
top: 50%; /*定位父级的50%*/
left: 50%; /*定位父级的50%*/
margin: -50px 0 0 -50px; /*上右下左。相对父元素的大小*/
}
(2)子绝父相 与 margin:auto 实现
.parent {
position: relative;
width: 600px;
height: 600px;
}
.child {
position: absolute;
width: 100px;
height: 100px;
top: 0; right: 0; bottom: 0; left: 0;
margin: auto;
}
(3)calc() 函数 实现
.parent {
width: 600px;
height: 600px;
}
.child {
position: relative;
width: 100px;
height: 100px;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
1、div 宽高未知—进行水平垂直居中
(1)子绝父相 与 transform 实现
.parent {
position: relative;
width: 600px;
height: 600px;
}
.child {
position: absolute;
width: 100px;
height: 100px;
top: 50%; /*定位父级的50%*/
left: 50%; /*定位父级的50%*/ /*用CSS3的transform*/
transform: translate(-50%, -50%);/*使transform中translate偏移的百分比值是相对于自身大小的*/
}
(2)flex布局 实现
.parent {
display: flex;
justify-content: center;
align-items: center;
}
(3)grid布局 实现
.parent {
display: grid;
}
.child {
justify-self: center;
align-self: center;
}
(4)table表格布局 实现
<div class="table">
<div class="parent">
<div class="child"> <div>
</div>
<div>
.table{
display: table;
}
.parent{
display: table-cell;
text-align: center;
vertical-align:middle;
}
.child{
diaplay:inline-block;
}
CSS居中布局技巧
本文详细介绍了在CSS中实现div元素水平垂直居中的多种方法,包括已知和未知宽高的情况,涵盖了绝对定位、Flex布局、Grid布局及Table布局等不同场景下的解决方案。
4386

被折叠的 条评论
为什么被折叠?



