栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > web前端

垂直水平居中的实现方式都有哪些?

web前端 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

垂直水平居中的实现方式都有哪些?

方法一:inline-block+text-align

<div >  <div >Demo</div></div><style>  .child {    display: inline-block;  }  .parent {    text-align: center;  }</style>
  • 优点:兼容性佳(甚至可以兼容 IE 6 和 IE 7)

方法二:table+margin

<div >  <div >Demo</div></div><style>  .child {    display: table;    margin: 0 auto;  }</style>
  • 优点:无需设置父元素样式 (支持 IE 8 及其以上版本)

方法三:absolute+transform

<div >  <div >Demo</div></div><style>  .parent {    position: relative;  }  .child {    position: absolute;    left: 50%;    transform: translateX(-50%);  }</style>
  • 优点:绝对定位脱离文档流,不会对后续元素的布局造成影响
  • 缺点:transform 为 CSS3 属性,有兼容性问题

方法四:flex+justify-content

Demo

.parent { display: flex; justify-content: center; } .parent { display: flex; } .child { margin: 0 auto; }

  • 优点:只需设置父节点属性,无需设置子元素
  • 缺点:有兼容性问题

垂直居中

方法一:table-cell + vertical-align

  <div >    <div >Demo</div>  </div>  <style>    .parent {      display: table-cell;      vertical-align: middle;    }  </style>
  • 优点:兼容性好(支持 IE 8,一下版本需要调整页面结构至 table)

方法二:absolute + transform

  <div >    <div >Demo</div>  </div>  <style>    .parent {      position: relative;    }    .child {      position: absolute;      top: 50%;      transform: translateY(-50%);    }  </style>
  • 优点:绝对定位脱离文档流,不会对后续元素的布局造成影响
  • 缺点:transform 为 CSS3 属性,有兼容性问题

方法三:flex + align-items

  <div >    <div >Demo</div>  </div>  <style>    .parent {      display: flex;      align-items: center;    }  </style>
  • 优点:只需设置父节点属性,无需设置子元素
  • 缺点:有兼容性问题

水平垂直居中

方法一:inline-block + text-align + table-cell + vertical-align

  <div >    <div >Demo</div>  </div>  <style>    .parent {      text-align: center;      display: table-cell;      vertical-align: middle;    }    .child {      display: inline-block;    }  </style>

方法二:absolute + transform

  <div >    <div >Demo</div>  </div>  <style>    .parent {      position: relative;    }    .child {      position: absolute;      left: 50%;      top: 50%;      transform: translate(-50%, -50%);    }  </style>

方法三:flex + justify-content + align-items

  <div >    <div >Demo</div>  </div>  <style>    .parent {      display: flex;      justify-content: center;      align-items: center;    }  </style>

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/274258.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号