CSS 实现盒子模型水平居中
- 使用margin: 0 auto; (只适用于子盒子有宽的时候)
- position 定位 (只适用于子盒子有宽度和高度的时候)
.parent {
position: relative
}
.child {
position: absolute;
top: 0;
left: 50%;
margin-left: /*子盒子的一半大小*/
}
- position + transform (子盒子有或没有宽高的时候都适用)
.parent {
position: relative
}
.child {
position: absolute;
top: 0;
left: 50%;
transform: translate(-50%, 0%);
}
- flex 布局(弹性布局)(子盒子有或没有宽高的时候都适用)
.parent {
display: flex;
justify-content: center; /*子元素水平排列方式*/
}
CSS 实现盒子模型垂直居中
- position 定位(适用于子盒子有宽度和高度的时候)
.parent {
position: relative;
}
.child {
position: absolute;
left: 0;
top: 50%;
margin-top: -25px; /*子盒子自身高度的一半*/
}
- position + transform(子盒子有或没有宽高的时候都适用)
.parent {
position: relative;
}
.child {
position: absolute;
left: 0;
top: 50%;
transform: translate(0%, -50%);
}
- flex 布局(子盒子有或没有宽高的时候都适用)
.parent {
display: flex;
align-items: center; /* 子元素垂直排列方式*/
}
CSS 实现盒子模型水平垂直居中
- position 定位(适用于子盒子有宽度和高度的时候)
.parent {
position: relative;
}
. child {
position: absolute;
top: 50%;
left: 50%;
margin-left: -25px;
margin-top: -25px;
}
- position + transform(子盒子有或没有宽高的时候都适用)
.parent {
position: relative;
}
.child {
position: absolute;
left: 0;
top: 50%;
transform: translate(-50%, -50%);
}
- flex 布局(子盒子有或没有宽高的时候都适用)
.parent {
display: flex;
justify-content: center; /*子元素水平排列方式*/
align-items: center; /* 子元素垂直排列方式*/
}
参考:www.cnblogs.com/plsmile/p/1…