我有两列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%;
}
}
答案 0 :(得分:2)
您可以添加此CSS:
.answer:only-of-type {
margin-left: auto;
}
来自MDN
:only-of-type CSS伪类表示没有的元素 同类型的兄弟姐妹。
* {
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;
}
&#13;
<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>
&#13;
答案 1 :(得分:0)
您可以添加一个height
设置为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>