Marcus Junius Brutus
Marcus Junius Brutus

Reputation: 27286

How can I use flexbox to achieve a tabular look with vertically aligned columns and zebra shading?

I'm using the following to implement vertically aligned columns using flexbox:

jsFiddle

.container {
  display: flex;
  flex-direction: row;
}
.column {
  display: flex;
  flex-direction: column;
  margin: 0.3em;
}
.column > div:first-child {
  font-weight: bold;
}
<div class='container'>
  <div class='column'>
    <div>food</div>
    <div>beans</div>
    <div>macademia nuts salted and coated with caramel</div>        
  </div>
  <div class='column'>
    <div>comments</div>
    <div>beans</div>
    <div>excellent nutrition</div>                
  </div>
  <div class='column'>
    <div>price</div>
    <div>3$</div>
    <div>20$</div>                
  </div>            
</div>

... the above works nicely but when I try to add zebra shading the margins between the colors become visible as shown in this jsfiddle.

How can I use flexbox to achieve a tabular look with vertically aligned columns and zebra shading?

Upvotes: 1

Views: 42

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 371489

Instead of margin use padding.

Apply the padding only to inner columns:

/* KEY RULE */
.column + .column > div {
  padding-left: 2em;
}

/* ORIGINAL CODE */
.container {
  display: flex;
  flex-direction: row;
}
.column {
  display: flex;
  flex-direction: column;
}
.column > div:first-child {
  font-weight: bold;
}
.column > div:nth-child(odd) {
  background: #dddddd;
}
<div class='container'>
  <div class='column'>
    <div>food</div>
    <div>beans</div>
    <div>macademia nuts salted and coated with caramel</div>
  </div>
  <div class='column'>
    <div>comments</div>
    <div>beans</div>
    <div>excellent nutrition</div>
  </div>
  <div class='column'>
    <div>price</div>
    <div>3$</div>
    <div>20$</div>
  </div>
</div>

Upvotes: 1

Related Questions