秋天招骋时间到了,很多人都需要换工作了。前端面试,总是会有些人跟我一个基本上难题,div居中法。在这儿,我将汇总一下常见的方式。

肯定本土化

父级原素(parent)选用相对定位(relative),必须垂直居中的原素(demo)选用绝对定位(absolute)。垂直居中原素往上偏位50%,往左边偏位50%,这时左端点坐落于核心,但是大家必须的是总体垂直居中,因此在偏位本身一半的高宽。(如下图)

html中div水平居中-垂直居中的多种方式-第1张图片

沒有挪动它本身总宽和极度的一半。

.parent { position: relative; width: 500px; height: 500px; border: solid red 1px; } .demo { position: absolute; width: 100px; height: 100px; border: solid blue 1px; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; }

延展性定心决。

根据灵便的合理布局设定竖直和水平居中。

.parent { width: 500px; height: 500px; border: solid red 1px; display: flex; // 竖直,水平居中 align-items: center; justify-content: center; } .demo { width: 100px; height: 100px; border: solid blue 1px; }

应用转换垂直居中。

当子原素不清楚一个人的间距和特定时,应用转换开展比例转移。

.parent { position: relative; width: 500px; height: 500px; border: solid red 1px; } .demo { position: absolute; border: solid blue 1px; top: 50%; left: 50%; transform: translate(-50%, -50%); } 垂直居中

之上三种方式全是常见的,自然也有别的垂直居中的方式,例如网格图合理布局,报表表格中合理布局这些。

评论(0条)

刀客源码 游客评论