Pavel Perevezencev
Pavel Perevezencev

Reputation: 2978

How to get half of width with FlexBox

I have 2 solutions: the first is to add a new div.cell to the seconddiv.row or use calc. Maybe there is another way to do this.

.row {
  display: flex;
}
.row:not(:last-child) {
  margin-bottom: 10px;
}
.cell {
  flex: 1;
  border: 1px solid red;
}
.cell:not(:last-child) {
  margin-right: 10px;
}
<div class="row">
  <div class="cell">cell 1.1</div>
  <div class="cell">cell 1.2</div>
</div>
<div class="row">
  <div class="cell" style="flex: 0.5">cell 1.2</div>
</div>

Upvotes: 0

Views: 102

Answers (2)

G-Cyrillus
G-Cyrillus

Reputation: 106008

You can use calc() to set width minus the margin in action .

  .row {
  display: flex;
}

.row:not(:last-child) {
  margin-bottom: 10px;
}

.cell {
  flex: 1;
  border: 1px solid red;
  box-sizing:border-box;
}

.cell:not(:last-child) {
  margin-right: 10px;
}

.cell:first-child:last-child {
  width: calc(50% - 5px);
  flex:none;
}
<div class="row">
  <div class="cell">cell 1.1</div>
  <div class="cell">cell 1.2</div>
</div>
<div class="row">
  <div class="cell">cell 1.1</div>
</div>

Upvotes: 2

Kfir Dadosh
Kfir Dadosh

Reputation: 1419

The straight forward way is to use flex: 0 0 50%;

.row {
  display: flex;
}
.row:not(:last-child) {
  margin-bottom: 10px;
}
.cell {
  flex: 0 0 50%;
  border: 1px solid red;
}
<div class="row">
  <div class="cell">cell 1.1</div>
  <div class="cell">cell 1.2</div>
</div>
<div class="row">
  <div class="cell">cell 1.2</div>
</div>

Upvotes: 2

Related Questions