对于一个未知宽高的盒子,如何让它水平垂直居中于父元素()
1. table
display: table;
使父元素的作用像table元素一样,display: table-cell;
使子元素的作用像td一样。给此时的子元素用vertical-align和text-align设置水平垂直居中,子元素其中的未知宽高的元素当然就相对子元素水平垂直居中了。
.table {
display: table;
}
.cell {
display: table-cell;
width: 100px;
height: 100px;
border: 1px solid #ccc;
vertical-align: middle;
text-align: center;
}
.cell span {
background: #ddd;
}hahaha
2. JS计算
.parent {
position: relative;
width: 100px;
height: 100px;
border: 1px solid #ccc;
}
.child {
position: absolute;
background: #ddd;
}hahaha
3. transform
transform:translate(tx[,ty])
定义2D转换。tx表示x方向偏移,ty表示y方向偏移。如果tx,ty为百分比的话,其参考值是元素本身的宽高,正适合未知宽高的居中定位。
.parent {
position: relative;
width: 100px;
height: 100px;
border: 1px solid #ccc;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #ddd;
}hahaha
4. flexbox(弹性容器布局)
.parent {
display: flex;
justify-content: center;
/* 设置弹性容器的item在主轴上居中 */
align-items: center;
/* 设置弹性容器的item在交叉轴上居中 */
width: 100px;
height: 100px;
border: 1px solid #ccc;
}
.child {
background: #ddd;
}hahaha
5. grid(网格布局)
.parent {
display: grid;
justify-items: center;
/* 在行中的对齐方式 */
align-items: center;
/* 在列中的对齐方式 */
width: 100px;
height: 100px;
border: 1px solid #ccc;
}
.child {
background: #ddd;
}hahaha
【对于一个未知宽高的盒子,如何让它水平垂直居中于父元素()】
推荐阅读
- 一个人的旅行,三亚
- 一个小故事,我的思考。
- 一个人的碎碎念
- 七年之痒之后
- 我从来不做坏事
- 异地恋中,逐渐适应一个人到底意味着什么()
- 迷失的世界(二十七)
- live|live to inspire 一个普通上班族的流水账0723
- 遗憾是生活的常态,但孝顺这件事,我希望每一个人都不留遗憾
- 装聋作哑,关系融洽