2012-04-24 126 views
5

我有一个问题,在HTML中居中div(垂直水平&)。我的代码看起来像这样:如何居中div?

<div id="container">SOME HTML</div> 

#container{ 
    width: 366px; 
    height: 274px; 
    margin: 50%; 
    top: -137px; 
    left: -188px; 
    position:absolute; 
} 

只有铬中心此div在屏幕中间。

+4

我可能失去了一些东西,但你怎么期待居中DIV如果你使用绝对定位?你是否假设所有屏幕都具有相同的大小和分辨率? – 2012-04-24 15:41:22

回答

1

该做的伎俩(垂直&水平):

#container{ 
    position: absolute; 
    width: 366px; 
    height: 274px; 
    left: 50%; 
    top: 50%; 
    margin-left: -183px; /* half width */ 
    margin-top: -137px; /* half height */ 
} 
7

这将居中<div>水平:

#container{ 
    width: 366px; 
    height: 274px; 
    margin: 0 auto; 
} 

垂直居中是不是很简单,你也许不得不使用JavaScript为,或尝试this css solution

1

你可以使用:

#container { 
    // Your other values, but remove position: absolute; 
    margin: 0 auto; 
} 

或者,你可以这样做:

#wrapper, #container { 
    border: 1px solid red; 
    height: 500px; 
    width: 600px; 
} 

#wrapper { 
    bottom: 50%; 
    right: 50%; 
    position: absolute; 
} 

#container { 
    background: yellow; 
    left: 50%; 
    padding: 10px; 
    position: relative; 
    top: 50%; 
} 

而你的HTML代码:

<div id="wrapper"> 
    <div id="container"> 
     <h1>Centered Div</h1> 
     <p> 
      This div has been centered within your browser window.</p> 
    </div> 
</div> 

这将居中<div>中间的浏览器窗口。

-1

应罚款只使用CSS:

这里是demo

#container{ 
    width: 366px; 
    height: 274px; 
    margin: 50%; 
    top: 50%; 
    left: 50%; 
    position:absolute; 
    top:0; 
    bottom:0; 
    left:0; 
    right:0; 
}​ 
+0

没有得到,它为什么是-1?这是错的吗? – AlexC 2012-04-24 16:01:42

2
#container{ 
    width: 366px; 
    height: 274px; 
    top: 50%; 
    left: 50%; 
    margin: -137px 0 0 -188px; 
    position:absolute; 
} 
+0

非常感谢! ;)现在它工作。 – What 2012-04-24 15:55:19

1

试试这个:

<div class="cont"> 
    <div class="box"></div> 
</div> 

的CSS:

.cont{ 
    background-color: tomato; 
    width: 600px; 
    height: 400px; 
    position: relative; 
} 
.box { 
    width:100px; 
    height:100px; 
    background-color: teal; 
    color:#fff; 
    position: absolute; 
    left: 50%; 
    top: 50%; 
    transform: translate(-50%, -50%) 
}