2017-02-26 40 views
1

相鄰的選擇器很適合在元素之間獲取邊距,例如卡片設計。但是如何在製作響應元素時使用flexbox保持相同的設計。這似乎只刪除第一個元素的邊距,而不是每一行的第一個元素。有沒有針對這個問題的優雅解決方案?理想情況下,8個元素在全部在一行或四行時看起來相同。使用css前景選擇器的響應式柔性盒設計

.container { 
 
    display: flex; 
 
    flex-wrap: wrap; 
 
} 
 

 
.card { 
 
    height: 250px; 
 
    width: 250px; 
 
    background-color: blue; 
 
} 
 

 
.card+.card { 
 
    margin-left: 10px; 
 
}
<div class="container"> 
 
    <div class="card"></div> 
 
    <div class="card"></div> 
 
    <div class="card"></div> 
 
    <div class="card"></div> 
 
    <div class="card"></div> 
 
    <div class="card"></div> 
 
    <div class="card"></div> 
 
    <div class="card"></div> 
 
</div>

代碼也jsbin:https://jsbin.com/cusekumiza

+0

與其在相鄰元素上使用「margin-left」,您可以在'.card'本身直接使用'margin'屬性。 –

+0

,如果你不想爲最後一張卡片使用第一張「margin-left」和最後一張卡片的「margin-right」,請嘗試在'.container'使用'justify-content:space-between;' –

+0

@MuraliKrishna與空間之間你得到可變間距。我想要固定的間距。 – Anders

回答

1

可以使用的方式,最敏感的框架中解決這個問題時,使用「行」容器「補償」左,右頁邊距,將其設定負,這樣的:

.container { 
     display: flex; 
     flex-wrap: wrap; 
     //this will "cancel" the margin on the left an right side 
     margin-left:-10px; 
     margin-right:-10px; 
     justify-content:space-between; //this is to justify block on left and right side 
    //but it will set auto margin between block, don't set if you don't care of the right side 
    } 
    .card { 
     height: 250px; 
     width: 250px; 
     background-color: blue; 
     margin: 10px; // you appli normally the margin for your block 
    } 

這裏是我的JS斌:https://jsbin.com/buwezudiju/1/edit?html,output