Skip to content

垂直水平居中的方法 ​

水平居中 ​

  • 如果元素为行内元素,给父元素设置 text-align:center
  • 如果元素宽度固定,可以设置左右 margin 为 auto ;
  • 如果元素为绝对定位,给父元素设置 position: relative ,元素设 left:0;right:0;transform: translateX(-50%);
  • flex 布局,justify-content: center
  • display 设置为 tabel-ceil

垂直居中 ​

  • display: table-cell,同时设置 vertial-align:middle
  • flex 布局,align-items:center
  • 绝对定位中设置 bottom:0,top:0 ,并设置 margin:auto
  • 绝对定位中固定高度时设置 top:50%,margin-top 值为高度一半的负值
  • 文本垂直居中设置 line-height 为 height 值

黑科技 ​

  • 为父元素设置 display: flex/grid 子元素设置 margin: auto

Released under the MIT License.