JS每日一题: 元素水平垂直居中的方式有哪些?

4,151 阅读1分钟

20190119问:

元素水平垂直居中的方式有哪些?

  • absolute加margin方案
  • fixed 加 margin 方案
  • display:table 方案
  • 行内元素line-height方案
  • flex 弹性布局方案
  • transform 未知元素宽高解决方案
absolute加margin方案
    div{
        position: absolute;
        width: 100px;
        height: 100px;
        left: 50%;
        top: 50%:
        margin-top: -50px;
        margin-left: -50px;
    }
fixed 加 margin 方案
    div{
        position: fixed;
        width: 100px;
        height: 100px;
        top: 0;
        right:0;
        left: 0;
        bottom: 0;
        margin: auto;
    }
display:table 方案
    div{
        display: table-cell;
        vertical-align: middle;
        text-align: center;
        width: 100px;
        height: 100px;
    }
行内元素line-height方案
    div{
        text-align: center;
        line-height: 100px;
    }
flex 弹性布局方案
    div{
        display: flex;
        align-items: center;
        justify-content:center
    }
transform 未知元素宽高解决方案
    div{
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%)
    }

往期

JS每日一题: 前端的缓存有哪些?都适用什么场景?区别是什么?
JS每日一题: Call,Apply,Bind的使用与区别,如何实现一个bind?
JS每日一题: 说说你对前端模块化的理解
JS每日一题: web安全攻击手段有哪些?以及如何防范

关于JS每日一题

JS每日一题可以看成是一个语音答题社区
每天利用碎片时间采用60秒内的语音形式来完成当天的考题
群主在次日0点推送当天的参考答案

  • 注 绝不仅限于完成当天任务,更多是查漏补缺,学习群内其它同学优秀的答题思路

扫描下方二维码即可加入答题