CSS-居中布局
2018-06-06 本文已影响0人
Crisyhuang
html 结构:
<div class="parent">
<div class="child">DEMO</div>
</div>
css代码:
-
水平居中
- inline-block + text-align
.parent{
text-align: center;
}
.child{
display: inline-block;
}
- table + margin
.child{
display: table;
margin: 0 auto;
}
- absolute + transform
.parent{
position: relative;
}
.child{
position: absolute;
left: 50%;
transform: translateX(-50%);
}
- flex + justify-content / margin
.parent{
display: flex;
justify-content: center;
}
.child{
margin: 0 auto;
}
-
垂直居中
- table-cell + vertical-align
.parent{
display: table-cell;
vertical-align: middle;
}
- absolute + transform
.parent{
position: relative;
}
.child{
position: absolute;
left: 50%;
transform: translateY(-50%);
}
- flex + align-items
.parent{
display: flex;
align-items: center;
}
-
水平居中 + 垂直居中
- inline-block + text-align + table-cell + vertical-align
.parent{
text-align: center;
display: table-cell;
vertical-align: middle;
}
.child{
display: inline-block;
}
- absolute + transform
.parent{
position: relative;
}
.child{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
- flex + justify-content
.parent{
display: flex;
justify-content: center;
align-items: center;
}