2012-04-24 141 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%) 
}