2017-01-30 97 views
2

我希望在我的所有柔性盒的左右兩側始終具有相同的空間距離。目前,我有這樣的代碼:第一個和最後一個柔性盒的邊距

body 
    background-color white 
    margin 0 0 
    padding 0 0 

.overlay 
    display flex 
    position absolute 
    background-color grey 
    cursor pointer 
    color #8e3433 
    flex-flow row nowrap 
    justify-content flex-start 
    height 40vh 
    width 100vw 
    bottom 0 
    left 0 
    margin 0 
    overflow-y hidden 
    overflow-x scroll 

.overlay .item-image 
    border-radius 5px 
    flex 1 1 auto 
    min-width 45.0vw 
    width 45.0vw 
    margin 0 2vw 0 2vw 
    border 1px solid yellow 

請參閱this小提琴爲例(如果它不顯示rightaway你必須選擇在最後的樣式代碼,只是按Enter鍵(在JSbin錯誤...)它應該顯示出來)。

第一個框的左邊我得到2vh而不是4vh。參見: enter image description here 在其他盒子之間它都很好(4vh)。 最後一個框右側沒有任何空間。見: enter image description here 所以我的問題: 1)如何獲得4vh在第一個盒子的左側?和 2)如何讓4vh在最後一個盒子的右邊?

我試着查找這個,看到使用容器填充的稍微不同的問題的解決方案。我更喜歡沒有調整容器填充的解決方案。

回答

1

更新回答

使用僞元素作爲柔性項目佔用空間:

ul { 
 
    list-style-type: none; 
 
    padding: 0; 
 
    margin: 0; 
 
    display: flex; 
 
    height: 300px; 
 
    overflow-x: auto; 
 
    width: 600px; 
 
    background: orange; 
 
} 
 
li { 
 
    margin-left: 30px; 
 
    background: blue; 
 
    color: #fff; 
 
    padding: 90px; 
 
    white-space: nowrap; 
 
    flex-basis: auto; 
 
} 
 
ul::after { 
 
    content: ""; 
 
    flex: 0 0 30px; 
 
}
<ul> 
 
    <li>Item 1</li> 
 
    <li>Item 2</li> 
 
    <li>Item 3</li> 
 
    <li>Item 4</li> 
 
</ul>


以前的答案

注:該解決方案如下可能不會因爲盒子是「過度約束」的工作(見: How can I stop the last margin collapsing in flexbox?

每個包廂有2vw的左,右頁邊距。

因此,對於第一個項目(沒有右邊距,因爲沒有以前的框)和最後一個項目的一半(沒有左邊距,因爲沒有附加框),邊緣空間將爲一半。

相反,試試這個:

.item-image { margin-left: 4vw } 
.item-image:last-child { margin-right: 4w } 
+0

我會盡力的。請注意,在我的小提琴中,在最後一個框之後沒有保證金(儘管它應該有一個右邊距)。任何想法爲什麼? – musicformellons

+1

http://stackoverflow.com/a/38997047/3597276 –

+0

你能否在這個小提琴中實現你給的解決方案:http://codepen.io/anon/pen/yJwKpW在我的小提琴中?因爲我沒有得到它的工作。 – musicformellons

0

你可以先用胎和最後孩子

.overlay .item-image:first-child { 
    margin-left: 4vw; 
} 

.overlay .item-image:last-child { 
    margin-right: 4vw; 
} 

PS 要小心;你沒有正確關閉覆蓋DIV

+0

順便說一句,你可以把它的工作不撓:https://jsbin.com/verejosabe/1/edit?html,css,輸出 – kiwi1342

+0

是的,但小提琴是一個簡單的例子...我的擴展案例需要flexbox。 – musicformellons

0

試試這個

body { 
    background-color: #fff; 
    margin: 0 0; 
    padding: 0 0; 
} 

.overlay { 
    display: flex; 
    position: absolute; 
    background-color: #808080; 
    color: #f00; 
    justify-content: space-between; 
    height: 40vh; 
    padding: 0 4vw; 
    bottom: 0; 
    left: 0; 
    margin: 0; 
    overflow-y: hidden; 
    overflow-x: scroll; 
} 

.overlay .item-image { 
    border-radius: 5px; 
    flex: 1 1 auto; 
    min-width: 45vw; 
    width: 45vw; 
    border: 1px solid #00f; 
} 

.overlay .item-image :last-child:after { 
    content: ""; 
    width: 30px; 
    height: 1px; 
    position: absolute; 
    left: 100%; 
    top: 0px; 
} 

現場演示 - https://jsbin.com/yeyemomili/1/edit?html,css,output

相關問題