zoukankan      html  css  js  c++  java
  • 面试题:垂直居中几种方法

    一、使用定位

    方法1.

    top和left分别为50%,在使用margin-left和margin-top设置负的宽高(图片也可以使用)

    条件:这种方法必须设置子盒子的宽高

    .father{ height:300px; 600px; background:yellow; overflow:hidden;}

    .child {boder: 1px black solid; background:white; text-aligin:center; 100px; height:50px;}

    .father {position: relative;}

    .child {position:absolute; top:50%; left:50%; margin-top:-25px; margin-left:-50px;}         

    方法2:

    top right bottom left 都设置为0 再使用margin:auto(图片也可)

    条件:父盒子必须设置宽高,子盒子不必须

    .father {height:300px; 600px; background:yellow; overflow:hidden;}

    .child {border:1px black solid; bakcground:white; text-align:center;}

    .father{position:relative;}

    .child{ position:absolute; top:0; left:0; right:0;bottom:0; margin:auto}

    方法3:

    top和left分别为50%,再使用transform:translate(-50%,-50%)(图片也可以用这种方式)

    条件:子盒子不需要设置宽高,缺点是兼容性不好

    .father {position:relative;}

    .child {position:absolute; top:50%; left:50%; transform:translate(-50%,-50%);}

    二、弹性盒子

    方法1

    设置主轴和交叉轴都居中,支持不同屏幕大小(图片也可以)

    条件:兼容性不好

    .father { display :flex; justify-content:center; align-items:center;}

    方法2

    .father {display :flex;} 

    .child{margin:auto}

    三、使用display:table-cell

    本来用于文本的垂直居中,可以将div设置为inline(图片也可以)

    .father {display:table-cell; text-align:center; vertical-align:middle;}

  • 相关阅读:
    vue项目中引用spreadjs方法
    使用Element的table合并单元格的问题(合并行)
    卸载mysql
    mac 下安装mySQL
    react中界面跳转 A界面跳B界面,返回A界面,A界面状态保持不变 localStorage方法
    react点击弹出带出值和点击跳转页面带出值
    ajax优缺点
    vue项目console.log报错
    性能优化
    对象生命周期
  • 原文地址:https://www.cnblogs.com/charon-66/p/13365494.html
Copyright © 2011-2022 走看看