如何将div与垂直和水平中心对齐

时间:2012-06-15 18:30:24

标签: html css

我想将div对齐到中心。

像这样

enter image description here

我尝试过margin-top,vertical-align

但它们也不起作用。

我还设置左边小于0px

但内部div仍然是左侧的0px

如果我想将div设为上图

如何修改css使其如上图所示?

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
div
{
    border:solid;
}
#outer
{
    position:absolute;
    height:100px;
    width:50px;
    left:50px;
    top:50px;
}
#inner
{
    background:white;
    height:20%;
    width:120%;
    left:-10px;
    margin-top:auto;
    margin-buttom:auto;
    vertical-align:middle;
}
</style>
</head>
<body>

<div id="outer">
    <div id="inner">abc</div>
</div>
</body>
</html>

4 个答案:

答案 0 :(得分:3)

试试这个 - http://jsfiddle.net/vn6Wx/

#inner
{
    background:white;
    height:40%;
    width:200%;
    position: relative;
    left:-50%;
    top: 25%;
    margin-top:auto;
    margin-buttom:auto;
    vertical-align:middle;
}

答案 1 :(得分:1)

在不使用JavaScript的情况下垂直对齐元素的唯一灵活方法是将其放在表格单元格中。

答案 2 :(得分:0)

检查一下..

http://jsfiddle.net/dmvcs/

#outer{
  position:absolute;
  height:100px;
  width:50px;
  left:50px;
  top:50px;
  border:2px solid red;
}

#inner{
  background:white;
  position:absolute;
  height:50px;
  width:100px;
  top:50%;
  left:50%;
  margin-top:-25px;
  margin-left:-50px;
  border:2px solid green;
}​

答案 3 :(得分:0)

你可以试试这个:

<!DOCTYPE html>
<html lang="en">
    <head>
        <style>
            html { height:100%; width:100%; }
            body { background-color: yellow; margin:0; padding:0; }
            #outer { width:100%; min-height:100%; background-color:red; position:absolute; }
            #inner { width:500px; height:500px; background-color:blue; position:relative; margin:10% auto; }
        </style>
    </head>
    <body>
        <div id="outer">
            <div id="inner">
            </div>
        </div>
    </body>
</html>
祝你好运!