2012-10-04 49 views
2

我有以下HTML代碼,其中每個場景div是設置寬度並向左漂浮。
我想整個.section_2塊到觀察口內居中不管屏幕尺寸,:如何在視口中居中元素?

<div id="wrapper"> 
    <div id="scroller"> 
    <section class="section_2"> 
     <div class="scene2B1" data-stellar-ratio="1.1"></div> 
     <div class="scene2B2" data-stellar-ratio="1.4"></div> 
     <div class="scene2B3" data-stellar-ratio="1.3"></div> 
     <div class="scene2B4" data-stellar-ratio="1.5"></div> 
     <div class="scene2B5" data-stellar-ratio="1.2"></div> 
    </section> 

回答

2

CSS。

.section_2 { margin: 0 auto; width: 800px; } 

注意:您必須設置寬度。

0

大多數的方式@SMacFadyen給了工作,但如果沒有(我還沒有想通,爲什麼它沒有有時),你可以嘗試時間:

.section_2 { 
     margin-left:400px;/* half the width*/ 
     left:-50%; 
     width: 800px; 
    } 

與另一個答案,你必須設置一個寬度。它似乎有點黑客,但它適用於我。

演示:http://jsfiddle.net/jdwire/EfSBA/1/z

要居中它在整個視口,而不是僅僅的父元素,你可以嘗試:

 position:fixed; 

但這可以有一些細微的副作用,所以確保它是你想

1

如果你想設置的div#包裝在視口的中心將自己定位是什麼,重要的是你做下列之一:

  1. 知道是什麼的div#包裝的確切寬度和高度將是
  2. 使用JavaScript來動態地修改高度和DIV#包裝的基礎上,用戶的寬視

我給您的選擇#1的示例代碼(選項#2是不同的是加入的JavaScript動態調整的div#包裝相同)

HTML:

<body> 
    <div id="wrapper"> 
    <div id="scroller"> 
     <section class="section_2"> 
     <div class="scene2B1" data-stellar-ratio="1.1"></div> 
     <div class="scene2B2" data-stellar-ratio="1.4"></div> 
     <div class="scene2B3" data-stellar-ratio="1.3"></div> 
     <div class="scene2B4" data-stellar-ratio="1.5"></div> 
     <div class="scene2B5" data-stellar-ratio="1.2"></div> 
     </section> 
    </div> 
    </div> 
</body> 

CSS:

div#wrapper { 
    width: 300px; /* Must define this */ 
    height: 300px; /* Must define this */ 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    margin-top: -150px /* This is HALF of the height times -1 */ 
    margin-left: -150px /* This is HALF of the width times -1 */ 
}