Advanced Positioning

Flexbox

Provides a more efficient way to layout, align, and distribute space among items in a container, even when their size is unknown and/or dynamic.

The main idea behind the flex layout is to give the container the ability to alter its items' width/height (and order) to best fill the available space (mostly to accommodate all kinds of display devices and screen sizes).

<div class="container">
    <div class="itemRed"></div>
    <div class="itemOrange"></div>
    <div class="itemYellow"></div>
</div>

After setting the CSS to use flexbox, the positioning changes as follows.

.container {
    display: flex;
}

Flexbox properties can be categorized into 2 main types:

  1. Container properties (flex-direction, flex-wrap, justify-content, align-items, align-content)

  2. Flex Item properties (order, flex, flex-grow, flex-shrink, align-self)

  1. Flex Container: This refers to the container that has display: flex; set to it.

  2. Flex Item: These are the individual children inside of the Flex Container

  3. Main-axis: By default is set from left to right.

  4. Cross-axis: By default is set from top to bottom.

As soon as display: flex is set on a container, these imaginary axes are going to work together to determine how the flex items inside of the flex container should move around and behave.

Here is an example:

<div class="container">
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
</div>

/* CSS flexbox example */

.container {
  display: flex;
  flex-direction: row;
  align-items: top;
  justify-content: center;
}

.square {
  width: 100px;
  height: 100px;
  background-color: #ccc;
  margin: 100px 0 100px 0;

}

.square:first-child {
  margin-top: 0;
}

.square:last-child {
  margin-top: auto;
  margin-bottom: 0;
}

More details and examples below:

Another external resource:

Last updated

Was this helpful?