This question already has answers here:
Center a DIV horizontally and vertically [duplicate]
                                
                                    (7个答案)
                                
                        
                                6年前关闭。
            
                    
我创建了一个迷宫,我想将smily div(“ highlight_lose”)居中到迷宫(“ main”)

#highlight_lose {
    width: 550px;
    height:550px;
    position: absolute;
    margin: 0 auto;
    top: 50%;
    bottom: 375px;


}


这是小提琴链接:
http://jsfiddle.net/uqcLn/30/

最佳答案

新答案

根据您给我的介绍,这是使用旧的忠实位置绝对方法的必需CSS代码。

#highlight_lose {
    height: 300px;
    width: 100%;
    position: absolute;
    top: 50%;
    margin-top: -150px;
}
div.sad_smileyface {
    width: 300px;
    height: 100%;
    position: relative;
    margin: 0 auto;
    ...
    [your graphic styling code here]
}


需要注意的一点是,我将包含div的宽度设置为100%,并将其垂直居中。然后,我将孩子笑脸div居中居中。这不是必需的,只是我做过的方法。如果高度改变,请调整#highlight_lose,如果宽度改变,请更新sad_smileyface

原始答案

如果高度至少为十进制(您的高度),则将父容器设置为position: relative(为确保确定),您应该能够在子div的容器上使用margin: auto;。这应该可以跨浏览器访问IE 6。

其他选项包括通过将边距设置为高度和宽度的一半来做方法。 margin: -275px -275px;

另外,CSS3的Flexbox模型也可以解决此问题,但是前缀很重,并且不受任何地方支持。

关于css - 将div垂直居中并水平居中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19234413/

10-14 13:28