麻烦帮我看一下,这个元素居中了没?

95 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第5天,点击查看活动详情

44年前我们把人送上月球,但在CSS中我们仍然不能很好实现垂直居中。

——James Anderson

image.png

居中,给人美感。在网页中,我们在多处需要实现居中。

fe8aae2e8cfb553a364e51cd02a1cd8.jpg

比如下面的:

小米商城,商品展示,图片文字水平居中。

image.png

京东商城,版心居中。

e63890ac8bfe4cdaab5376a8e4947a5f_tplv-k3u1fbpfcp-watermark.png

水平居中

1.行内级元素:

  • 设置父级元素text-align属性为center。

我们给父级元素a设置了text-align: center;text-align属性能够被继承,所以,图片在父级元素a中水平居中,文字在p标签中水平居中。

2.块级元素:

  • 设置当前块级元素(宽度) margin: 0 auto;

3.绝对定位

  • 元素有宽度情况下, left: 0;right: 0; margin: 0 auto;

4.flex

  • justify-content: center;

垂直居中

1.行高(令单行文字垂直居中)。

image.png

令line-height = 文字所在盒子高度,文字将垂直居中显示。

2.绝对定位

  • 元素有高度情况下, top: 0;bottom: 0;margin: auto 0;

  • 缺点:

    (1) 必须使用定位(脱离标准流)。

    (2) 需要给元素设置高度。

3.flex布局

align-items:center;

  • 缺点: flex container中所有的元素都会垂直居中显示。

4.定位加形变 position/translate

分两步走

1.让需要居中的元素向下位移父级元素content高度的50%。

2.让需要居中的元素向上位移自身高度的50%。

margin-top的百分比是相对于包含块(父元素)的宽度。

margin-top: 50%; 
position: relative;
top: 50%;
transform: translate(0, -50%);`