Jaeeun Lee
Jaeeun Lee

Reputation: 3196

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

Upvotes: 1

Views: 53

Answers (2)

Hp93
Hp93

Reputation: 1535

You can add an invisible div with height set to 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>

Upvotes: 0

sol
sol

Reputation: 22939

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>

Upvotes: 2

Related Questions