Jaeeun Lee Jaeeun Lee - 1 year ago 51
CSS Question

Flexbox align column to the right if there is only one column

I have a two column flexbox layout. However, sometimes there is only one column, in which case the column should be aligned to the right. Currently the column is aligned to the left.

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%;
}
}

Answer Source

You can add this CSS:

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

From MDN

The :only-of-type CSS pseudo-class represents an element that has no siblings of the same type.

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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download