2014-09-22 363 views
0

我已經找過這個,但找不到任何好幫助。這很簡單 - 我想將div粘貼在頁面的絕對頂部,然後讓它居中。當我做了position: fixed我也寫了top:0pxleft:0px然後搞亂了定位。幫幫我?將一個div居中置於頁面頂部(僅限CSS!)

+0

請查閱[水平對齊](http://www.w3schools.com/css/css_align.asp)和[Postioning(http://www.w3schools.com /css/css_positioning.asp) – Grice 2014-09-22 17:50:50

回答

0

使用position:fixedtop:0px - 爲div在頂部和left:50%爲div在中間。

1

您需要設置一個寬度,然後設置margin: auto,使其水平居中。

.container { 
 
    position: relative; 
 
    background: #eee; 
 
} 
 
.positioned { 
 
    position: fixed; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
    width: 50%; 
 
    margin: auto; 
 
    background: #ccc; 
 
    text-align: center; 
 
}
<div class="container"> 
 
    <p>Some text</p> 
 
    <p>Some text</p> 
 
    <p>Some text</p> 
 
    <p>Some text</p> 
 
    <div class="positioned">Content here</div> 
 
</div>