2013-07-04 43 views
3

試圖水平中心和作物內中心作物的div(如果需要)另一種div中一個div。如何水平其他分區

有可能實現與背景圖像此相同的效果,但在這種情況下,我的內容是不是一個單一的形象。

小提琴:http://jsfiddle.net/7aMhY/1/

HTML:

<div class="poster_container"> 
    <div class="poster_row"> 
    <div class="poster" style="width: 210px;">1</div> 
    <div class="poster" style="width: 210px;">2</div> 
    <div class="poster" style="width: 210px;">3</div> 
    <div class="poster" style="width: 210px;">4</div> 
    <div class="poster" style="width: 210px;">5</div> 
    </div> 
</div> 

CSS:

.poster_container { 
    text-align: center; 
    border: dotted; 
    border-color: red; 
    background-color: #0ff; 
    margin: auto; 
    overflow:hidden; 
} 
.poster_row { 
    text-align: center; 
    margin: auto; 
    display: inline-block; 
    white-space:nowrap; 
    oveterflow:hidden; 
    border: dotted; 
    border-color: blue; 
    max-width: 100%; 
} 
.poster { 
    border: dotted; 
    display: inline-block; 
    border-color: green; 
    background-color: green; 
    height: 315px; 
    font-size:280px; 
    color: white; 
} 

只要poster_container DIV比poster_row DIV更寬,內容被居中。但是一旦poster_row更寬,它會收割,但它的內容只剩下左邊,並且僅在右邊裁剪。

我想有從兩側內poster_row DIV中心和農作物也同樣。外部div將是視口的100%,因此其寬度是任意的。理想情況下,我希望內部div具有任意寬度,因此我可以在不更改CSS的情況下輕鬆更換內容。

+0

我不認爲這可以用PU做對於js,您可以在海報行上保留50%左右的空白,然後再加上海報行寬的一半,這將使海報行橫向居中。但我想不出什麼把我的頭頂部僅適用於CSS – Huangism

回答

2

我想我明白了:

我讓你添加前綴和刪除最大寬度值

.poster_row { 
    margin: auto; 
    text-align: center; 
    display: inline-block; 
    white-space:nowrap; 
    overflow:hidden; 
    border: dotted; 
    border-color: blue; 
    position: absolute; 
    left: 50%; 
    transform:translate(-50%,0); 
} 
+0

這會對'.poster_container'的高度產生影響,但是解決了這個問題。小提琴在這裏:http://jsfiddle.net/7aMhY/4/ – vee

+0

這工程。使用margin-left和width的另一個解決方案也可以正常工作,我也注意到了一個警告。 – pliny

1

如果您poster_row的寬度不會改變加:

.poster_row { 
    text-align: center; 
    margin: auto; 
    display: inline-block; 
    white-space:nowrap; 
    overflow:hidden; 
    border: dotted; 
    border-color: blue; 
    position:absolute; 
    left: 50%; 
    margin-left: -525px; 
    width: 1050px; 
} 

否則你要計算寬度和利潤率左將JS

+0

實現這個作爲OP表示:「理想情況下,我想內的div有任意寬度爲好,這樣我就可以輕鬆更換內容,而不改變CSS 「。 – Huangism

+0

理想的寬度是任意的,但是這個解決方案工作正常。一個警告:我必須設置overflow-x:隱藏在包含poster_container的div中以防止水平滾動條。 – pliny