Cross browser div center alignment using CSS

前端 未结 4 1063
醉话见心
醉话见心 2020-12-08 03:22

What is the easiest way to align a div whose position is relative horizontally and vertically using CSS ? The width and the height of the div

4条回答
  •  难免孤独
    2020-12-08 03:34

    Horizontal centering is only possible if the element's width is known, else the browser cannot figure where to start and end.

    #content {
        width: 300px;
        margin: 0 auto;
    }
    

    This is perfectly crossbrowser compatible.

    Vertical centering is only possible if the element is positioned absolutely and has a known height. The absolute positioning would however break margin: 0 auto; so you need to approach this differently. You need to set its top and left to 50% and the margin-top and margin-left to the negative half of its width and height respectively.

    Here's a copy'n'paste'n'runnable example:

    
    
        
            SO question 2935404
        
        
        
            
    content

    That said, vertical centering is usually seldom applied in real world.

    If the width and height are really unknown beforehand, then you'll need to grab Javascript/jQuery to set the margin-left and margin-top values and live with the fact that client will see the div quickly be shifted during page load, which might cause a "wtf?" experience.

提交回复
热议问题