How to center a div vertically?

后端 未结 4 498
忘掉有多难
忘掉有多难 2021-01-01 19:54

I have a div that I want to center horizontally and vertically.

For the horizontal issue everything is great, but I have a problem with the vertical ali

相关标签:
4条回答
  • 2021-01-01 20:46

    First off, treating non-table markup as tables (with display:table and friends) isn't cross-browser. I don't know which browsers you need to support but certainly IE6 won't do this. But, if your targeted browser do all support display:table I can give you some tips.

    The vertical centering approach you're looking for (using table layout) depends on having a TD with vertical-align:middle, then inside of that a single block element will vertically center. So I think what you want is:

    #parent { display:table-cell; vertical-align:middle; }
    #child { /* nothing necessary, assuming it's a DIV it's already display:block */ }
    

    It's ok to use table-cell with no surrounding table-row and table, the browser infers the needed table wrapping elements for you.

    0 讨论(0)
  • 2021-01-01 20:47

    If you only have to support browsers that support transform (or its vendor prefixed versions), use this one weird old trick to vertically align elements.

    #child {
        position: relative;
        top: 50%;
        transform: translateY(-50%);
    }
    

    If you have to support older browsers, you can use a combination of these, but they can be a pain due to the differences in rendering block vs table.

    #parent {
        display: table;
    }
    
    #child {
         display: table-cell;
         vertical-align: middle;
    }
    

    If your height is fixed and you need to support those really old, pesky browsers...

    #parent {
       position: relative;
    }
    
    #child {
       height: 100px;
       position: absolute;
       top: 50%;
       margin-top: -50px;
    }
    

    If your height is not fixed, there is a workaround.

    See it on jsFiddle.

    0 讨论(0)
  • 2021-01-01 20:52

    here is another way when you don't know the inner div size or whatever, you may use % here and there to fix the "centering" ....

    the idea is that your top value is half the height of your child element as to create the centering illusion

    Here's the code:

    <div id="parent">
        <div id="child">
                hello
        </div>
    </div>
    

    and for the styling:

    #parent {
       position: relative;
        height: 300px;
        width:200px;
        background-color:green;
    }
    
    #child {
       height: 50%;
       width: 50%;
        position:relative;
        top:25%;
        left:25%;
       background-color:red;
    }
    

    Here you can see it in action http://jsfiddle.net/Wabxv/

    0 讨论(0)
  • 2021-01-01 20:55

    Having the parent property as, display:table and child property as display: table-cell and vertical-align: middle worked for me.

    0 讨论(0)
提交回复
热议问题