Week 9 Notes

Flexbox Review

Flexbox is a set of CSS properties that help make it easy to create more structured layouts with your HTML. Flexbox is very good at putting elements into rows and columns, and centering elements within each other. 

To follow along, create a new HTML and css file that are linked together and open them up in Chrome and Sublime Text/whatever text editor you’re using.

HTML
<!DOCTYPE html>
<html>
<head>
  <title>Flexbox Demo</title>
  <link rel="stylesheet" href="assets/css/main.css">
</head>
<body>
  <div class="container">
    <div class="item1">1</div>
    <div class="item2">2</div>
    <div class="item3">3</div>
  </div>
</body>
</html>

CSS
.container {
  display: flex;
  padding:10px;
  background-color: seagreen;
  min-height: 200px;
}

.container div {
  margin: 10px 10px;
  width: 100px;
  height: 100px;
  background-color: bisque;
}

If you’ll notice, we’ve created a container in the div that holds 3 more items. When you use flexbox, you’ll always want a container housing it. In fact, even if you’re not using flexbox, it’s a good idea to keep elements contained in each other.

To use flexbox, all you have to do is set the container to display: flex; in the CSS, which we’ve already done. Comment this line of code in and out to see how it’s affected.


flex-direction

By default, the main axis is the horizontal one. That’s why, in the above example, it defaulted to this without us having to do any other work. It’s important to keep this in mind as you create layouts with flexbox.

To switch the orientation, you can add:
flex-direction: column;

If we try this, the main axis is vertical and the cross axis horizontal, resulting in the items being stacked vertically.