ndan
ndan

Reputation: 25

Use flex-box to display table with columns having unequal width

I am using flex-box to create a responsive table having 3 columns of the following widths: 80%, 15% and 5%. Further, whenever the screen size changes, I want the width % to remain the same i.e it should always be in the ratio 80%, 15%, 5%

I am using the following CSS for the 3 columns:

styles.css

.container{
  display: flex;
}
.firstColumn {
  padding: 12px;
  width: 80%;
  flex: 8;
}
.secondColumn {
  padding: 12px;
  width: 15%;
  flex: 1.5;
}
.thirdColumn {
  padding: 12px;
  width: 5%;
  flex: 0.5;
}

index.html

<div className={styles.container}>
  <div className={styles.firstColumn}> A </div>
  <div className={styles.secondColumn}> B </div>
  <div className={styles.thirdColumn}> C </div>
</div>

Is there an elegant way of doing this? Would using grid or table be more appropriate in this case?

Upvotes: 0

Views: 2060

Answers (1)

nicael
nicael

Reputation: 18997

You're using flexbox, and there's a built-in way to define the relative size in it

.container {
  display: flex;
  color:white;
  font-size:30px;
}

.box-1 {
  flex: 80;
  background: red;
}

.box-2 {
  flex: 15;
  background: green;
}

.box-3 {
  flex: 5;
  background: blue;
}
<div class="container">
  <div class="box-1">A</div>
  <div class="box-2">B</div>
  <div class="box-3">C</div>
</div>

Upvotes: 2

Related Questions