CSS垂直水平居中
定宽高元素居中
①absolute + 负margin(需要知道子元素的宽高)
②absolute + margin auto(需要知道子元素的宽高)
③absolute + calc(需要知道子元素的宽高)
html代码
<body>
<div class="parent">
<div class="child size"></div>
</div>
</body>
css 代码 公共样式
*{
margin: 0px;
padding: 0px;
}
.parent {
border: 1px solid red;
width: 300px;
height: 300px;
}
.child {
background: green;
}
.child.size {
width: 100px;
height: 100px;
}
方式一 absolute + 负margin
.parent{
position:relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
效果如下
方式二 absolute + margin auto
.parent{
position:relative;
}
.child {
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
margin: auto;
}
效果如下
方式三 absolute + calc
.parent{
position:relative;
}
.child {
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
calc() 计算属性
top:calc(50% - 50px) 50%是相对于元素左上角的定位 与方式一思路是一样的
top:calc(50% - 50px) 50
效果如下
不定宽高元素水平垂直居中
① absolute + transform
② text-align + line-height
③ css-table
④ flex
⑤ grid
html代码
<div class="parent">
<div class="child"></div>
</div>
css代码
*{
margin: 0px;
padding: 0px;
}
.parent {
border: 1px solid red;
width: 300px;
height: 300px;
}
.child {
background: green;
}
效果如下
方式一 absolute + transform
.parent{
position:relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
该方法与定宽高方式一思路一样,只是由于transform的translate属性在设置百分比时,其是相对于自身的宽和高,所以可以不用定子元素的宽高
效果如图:
方法二 text-align + line-height
.parent{
text-align: center;
font-size: 0px;
line-height: 300px;
}
.child {
font-size: 16px;
display: inline-block;
line-height: initial;
}
其思路是将div块级元素转化为行内元素,利用text-align做到水平居中;line-height垂直方向做到居中
效果如图:
方式三 css-table
.parent{
display: table-cell;
text-align: center;
vertical-align: middle;
}
.child {
display: inline-block;
}
通过display:table-cell 将div块级元素以表格单元格显示。
效果如图
方式四 flex 极其优雅 兼容性较好
.parent{
display: flex;
justify-content:center;
align-items:center;
}
效果如图
方式五 grid 兼容性不如flex
.parent{
display: grid;
}
.child {
align-self: center;
justify-self: center;
}
效果如图