Triangle Front End Notes - CSS Layout Techniques

CSS Layout Techniques

by Bermon Painter (Meetup) (Twitter)

Hardest problem on web...

Horizontally and vertically centered box.

body {
  display: flex;
  align-items: center;
  justify-content: center;
}
.box {
  height: 100px;
  width: 100px;
}

Previous best solution was floats with .clearfix. This improved with psuedo-selectors, but was still not ideal.

Flexbox & Grid

(Not competing standards)

Most flexbox work is done on parent element, not the child.

.container {
  display: flex;
  flex-direction: row; // row, row-reverse, column, column-reverse
  flex-wrap: wrap; // wrap, wrap-reverse (start laying out at bottom and work up
  flex-flow: row nowrap; // defaults, combines two properties above

  // how to fill space around boxes vertically
  justify-content: flex-start; // flex-start, flex-end, center, space-between, space-around

  // how to fill space around boxes horizontally
  align-items: stretch; // stretch, flex-start, flex-end, center, space-between, space-around
}
.box {
}

Flexbox Primer

.container {
  display: flex;
}
.box {
  order: 0;
  &:nth-child(1) {
    order: -1; // move second child to start
  }
}
.container {
  display: flex;
}
.box {
  flex-grow: 1;
  // also flex-shrink: 1;
  &:nth-child(2) {
    flex-grow: 2; // third box twice as wide as other boxes
  }
}
.container {
  display: flex;
}
.box {
  flex-grow: 1;
  &:nth-child(2) {
    flex-basis: 200px; // third box won't always be exactly 200px due to fuzzy math
  }
}

Resources