2017-07-27 48 views
1

我有兩列Flexbox佈局。但是,有時只有一列,在這種情況下,列應該對齊到右側。目前該列與左側對齊。如果只有一列,Flexbox將列對齊到右側

https://codepen.io/sleepydada/pen/rzVRxL

HTML:

<div class="answers"> 
    <div class="answer">first answer</div> 
    <div class="answer">second answer</div> 
</div> 
<div class="answers"> 
    <div class="answer">first answer</div> 
</div> 

SCSS:

* { 
    box-sizing: border-box; 
} 

.answers { 
    border: 2px solid black; 
    margin-bottom: 20px; 
    display: flex; 
    flex-wrap: wrap; 
    justify-content: space-between; 

    &:first-of-type { 
    background: #ccc; 
    } 

    .answer { 
    background: crimson; 
    margin: 20px 0; 
    border: 1px solid blue; 
    flex: 0 0 33.3333%; 
    } 
} 

回答

2

您可以添加此CSS:

.answer:only-of-type { 
    margin-left: auto; 
} 

MDN

唯一類型的CSS僞類表示沒有 兄弟姐妹的相同類型的元素。

codepen

* { 
 
    box-sizing: border-box; 
 
} 
 

 
.answers { 
 
    border: 2px solid black; 
 
    margin-bottom: 20px; 
 
    display: flex; 
 
    flex-wrap: wrap; 
 
    justify-content: space-between; 
 
} 
 

 
.answers:first-of-type { 
 
    background: #ccc; 
 
} 
 

 
.answers .answer { 
 
    background: crimson; 
 
    margin: 20px 0; 
 
    border: 1px solid blue; 
 
    flex: 0 0 33.3333%; 
 
} 
 

 
.answers .answer:only-of-type { 
 
    margin-left: auto; 
 
}
<div class="answers"> 
 
    <div class="answer">first answer</div> 
 
    <div class="answer">second answer</div> 
 
</div> 
 
<div class="answers"> 
 
    <div class="answer">first answer</div> 
 
</div>

0

您可以height集中添加一個不可見的div 0

* { 
 
    box-sizing: border-box; 
 
} 
 

 
.invisible { 
 
    height: 0; 
 
    border: none !important; 
 
} 
 

 
.answers { 
 
    border: 2px solid black; 
 
    margin-bottom: 20px; 
 
    display: flex; 
 
    flex-wrap: wrap; 
 
    justify-content: space-between; 
 
} 
 
.answers:first-of-type { 
 
    background: #ccc; 
 
} 
 
.answers .answer { 
 
    background: crimson; 
 
    margin: 20px 0; 
 
    border: 1px solid blue; 
 
    flex: 0 0 33.3333%; 
 
}
<div class="answers"> 
 
    <div class="answer">first answer</div> 
 
    <div class="answer invisible"><!--invisible div--></div> 
 
    <div class="answer">second answer</div> 
 
</div> 
 
<div class="answers"> 
 
    <div class="answer invisible"><!--invisible div--></div> 
 
    <div class="answer">first answer</div> 
 
</div>

+0

在我看來,這將是一個壞習慣的例子。 –

+1

我同意這可能是對這個問題的殺戮,但在某些情況下,這個概念可以得心應手。 – Hp93