Alejandro
Alejandro

Reputation: 2326

CSS Flexbox - aligning cells column correctly

Traditionally, I would stick with html table, but in my app I have to add some interaction in this "table" (I will be implementing collapsible window between rows with event listener, etc).

So I decided to use flexbox and emulate like a html table.

However I am having trouble for each row to align correctly column wise.

.container {
  display: flex;
  flex-wrap: wrap;
  border: black 1px solid;
  width: 100%;
}

.row {
  display: flex;
  height: 40px;
  width: 100%;
  align-items: center;
}

.cell {
  padding-right: 25px;
  padding-left: 20px;
  align-items: center;
  font-size: 20px;
  border-right: 1px solid salmon
}
<div class="container">
  <div class="row">
    <div class="cell">Descrption</div>
    <div class="cell">Amount per Month</div>
    <div class="cell">Amount per year</div>
  </div>
    <div class="row">
    <div class="cell">Income</div>
    <div class="cell">$20,000</div>
    <div class="cell">$45,000</div>
  </div>
</div>

As you can see, the right-border of each cells does not align correctly.

Is it possible using flex-box to achieve this? Or is my implementation is wrong?

Note: I cannot use any JavaScript nor jQuery for this one.

Upvotes: 0

Views: 56

Answers (2)

repzero
repzero

Reputation: 8412

Since you are using display flex. you can use flex-basis property

See snippet below

.container {
  display: flex;
  flex-wrap: wrap;
  border: black 1px solid;
  width: 100%;
}

.row {
  display: flex;
  height: 40px;
  width: 100%;
  align-items: center;
}
.row .cell{
  flex:0 0 30%;
}

.cell {
  padding-right: 25px;
  padding-left: 20px;
  align-items: center;
  font-size: 20px;
  border-right: 1px solid salmon
}
<div class="color-div">

</div><div class="container">
  <div class="row">
    <div class="cell">Descrption</div>
    <div class="cell">Amount per Month</div>
    <div class="cell">Amount per year</div>
  </div>
    <div class="row">
    <div class="cell">Income</div>
    <div class="cell">$20,000</div>
    <div class="cell">$45,000</div>
  </div>
</div>

Upvotes: 2

Rakesh
Rakesh

Reputation: 216

It is quite simple. Just give equal width to cell. e.g.:

.container {
  display: flex;
  flex-wrap: wrap;
  border: black 1px solid;
  width: 100%;
}

.row {
  display: flex;
  height: 40px;
  width: 100%;
  align-items: center;
}

.cell {
  padding-right: 25px;
  padding-left: 20px;
  align-items: center;
  font-size: 20px;
  border-right: 1px solid salmon;
  width: 33%;
}
<div class="container">
  <div class="row">
    <div class="cell">Descrption</div>
    <div class="cell">Amount per Month</div>
    <div class="cell">Amount per year</div>
  </div>
    <div class="row">
    <div class="cell">Income</div>
    <div class="cell">$20,000</div>
    <div class="cell">$45,000</div>
  </div>
</div>

Upvotes: 1

Related Questions