cevincheung

做前端的时候水平居中很容易做到。垂直居中一般怎么做呢?

  •  1
     
  •   cevincheung ·
    cevin · Aug 15, 2015 · 5763 views
    This topic created in 3959 days ago, the information mentioned may be changed or developed.
    //水平居中是在一条横向的直线的中点是吧?
    

    水平居中的话一般都是margin:0 auto;就可以了。垂直呢?有什么简单的方法么?

    27 replies    2015-08-16 11:34:01 +08:00
    cqcn1991
        1
    cqcn1991  
       Aug 15, 2015 via iPhone
    …老大难问题…
    Septembers
        2
    Septembers  
       Aug 15, 2015 via Android
    display: table-cell; vertical-align: middle;
    但是要 定宽,定高
    sadscv
        4
    sadscv  
       Aug 15, 2015 via Android
    用line-height去控制。
    br00k
        5
    br00k  
       Aug 15, 2015   ❤️ 1
    http://www.zhangxinxu.com/wordpress/2013/11/margin-auto-absolute-%E7%BB%9D%E5%AF%B9%E5%AE%9A%E4%BD%8D-%E6%B0%B4%E5%B9%B3%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%AD/

    其实也很容易,比较神奇的是第三个。还有一种是inline元素参照来垂直居中,方式很多,看自己需要使用。
    yakczh
        7
    yakczh  
       Aug 15, 2015
    table valign="middle"
    neone
        8
    neone  
       Aug 15, 2015
    lxrmido
        10
    lxrmido  
       Aug 15, 2015
    top:50%;
    margin-top:-50%;
    airyland
        11
    airyland  
       Aug 15, 2015
    top 50% 然后 margin translate -50% 就不用固定宽高了
    mok502
        13
    mok502  
       Aug 15, 2015 via Android
    ik0r
        14
    ik0r  
       Aug 15, 2015
    比较先进的浏览器的话, 就用

    position:absolute;
    top: 50%;
    left: 50;
    transform: translate(-50%, -50%);
    nine
        15
    nine  
       Aug 15, 2015
    jiongxiaobu
        18
    jiongxiaobu  
       Aug 15, 2015 via Android
    0 0根据不同情况有不同的方法
    aivier
        19
    aivier  
       Aug 15, 2015
    css-tricks上面有一个向导,可以根据不同需求告诉你该怎么做
    tinyhill
        20
    tinyhill  
       Aug 15, 2015
    容器 display: -webkit-box; -webkit-box-pack: center; -webkit-box-align: center;
    arzusyume
        21
    arzusyume  
       Aug 15, 2015
    不怎么动脑子的写法...
    position:absolute;
    top: 0;
    bottom: 0;
    margin: auto

    加上left: 0, right:0 还能绝对居中...
    an168bang521
        22
    an168bang521  
       Aug 15, 2015
    .test{width: 400px;height: 400px;background: orange;position: absolute;top: 50%;left: 50%;margin: -200px 0 0 -200px;}
    我是这么写的;
    Clauz
        23
    Clauz  
       Aug 15, 2015   ❤️ 2
    jsonline
        24
    jsonline  
       Aug 15, 2015 via Android
    不会搜索?
    guoqiao
        25
    guoqiao  
       Aug 15, 2015 via iPhone
    @Clauz 终于有人贴出这个链接了。读了它,再也不操心居中问题。
    yuandong
        27
    yuandong  
       Aug 16, 2015
    用transform
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1371 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 82ms · UTC 17:07 · PVG 01:07 · LAX 10:07 · JFK 13:07
    ♥ Do have faith in what you're doing.