How to center a div vertically?

后端 未结 4 502
忘掉有多难
忘掉有多难 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: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:

    hello

    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/

提交回复
热议问题