对于一个未知宽高的盒子,如何让它水平垂直居中于父元素()

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

【对于一个未知宽高的盒子,如何让它水平垂直居中于父元素()】

    推荐阅读