CSS实现水平垂直居中

水平居中

  1. 若是行内元素,设置其父元素 text-align: center;
  2. 若是块级元素,该元素设置 margin: 0 auto;
  3. 使用flex 布局,父元素设置为 display: flex; justify-content: center;
  4. 使用 transform 属性,设置父元素 position: relative; ,子元素 position: absolute; left: 50%; transform: translate(-50%, 0)
  5. 使用绝对定位且宽度固定,子元素设置为负值的 margin-left
  6. 如果元素为绝对定位,设置父元素 postion: relation;,该元素设置为 left: 0; right: 0; margin: auto;

垂直居中

单行文本

若元素是单行文本,则可设置该元素的 line-height 等于父元素高度。

元素高度不定

  1. 将父元素显示方式设置为表格 display: table; ,子元素设置 display: table-cell; vertial-align: middle
  2. 使用 flex 布局,设置父元素 display: flex; align-center: center;
  3. 使用 transform 属性,设置父元素 position: relative; ,子元素 position: absolute; top: 50%; transform: translate(0, -50%)

元素高度固定

  1. 绝对定位固定高度时,设置子元素为 top: 50%;margin-top 为一半高度的负值
  2. 绝对定位固定高度时,设置子元素为 top: 0; bottom: 0; margin: auto 0;

总结

水平居中的方法较为简单,一般情况下使用 text-align: centermargin: 0 auto 即可。

我们发现,flex 布局、transform 属性和绝对定位几种方法同时适用于水平和垂直居中。

这些信息可能会帮助到你: 关于我们 | 侵权删除 | 捐赠支持

优惠推广:外卖红包天天领,下单享省钱福利~
文章名称:CSS实现水平垂直居中
文章链接:https://www.bysjb.cn/css-center.html
THE END
分享
二维码
打赏
< <上一篇
下一篇>>