skip navigation

FlexBox 1

Layout Example

Flexboxes exist inside a parent element and so the first thing to do is set the parent to flex:

display: flex;

And with just those two words all the child elements will be displayed as flex boxes.

As long as these child elements have some width, either by some content or because the width is defined you get something like this.

.flex-parent {
  display: flex;
  background: wheat;
}

.flex-parent > div {
  width: 100px;
  height: 100px;
  margin: 25px;
  background-color: RosyBrown;
}

(NB. These child divs have a margin of 25px. These margins do NOT collapse into one another. But it’s more usual in this situation to use the CSS property gap)

Next the two boxes are given a ratio factor.

nav {
  flex: 1;
}
article {
  flex: 5;
}

These two numbers mean that the <article> is 5 times wider than the <nav> element.

The two boxes below are flex boxes.

Layout with Flexbox

This section along with the side navigation is all done with flexbox.

This layout can easily be converted for mobile using the code:

@media (max-width: 600px) { .layoutexample { flex-direction: column; } }

The default value is for flexboxes to flow from L to R in a row. By changing this they stack vertically: ideal for a mobile screen.

Messy example

This is an example of a list with fixed width child <li>s in em’s.

ol {
   display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 10px;
}
li {
  width: 13em;
  padding: 1em;
  text-align: center;
  background-color: dodgerblue;
}
  1. the partridge
  2. media pins
  3. saichania
  4. ornitholestes
  5. Tawa
  6. and another one
  7. syphilis
  8. and another one
  9. Joke Porches are no joke
  10. runny turds
  11. Fine women on children's bikes.
View the CSS for this page
.flexsimple {
  display: flex;
  background: wheat;
  margin: 1em 0 2em;
  /* width: 459px; */
}

.flexsimple > div {
  width: 100px;
  height: 100px;
  background-color: RosyBrown;
  margin: 25px;
}

.flex {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 10px;
  background-color: #159;
}

.flex li {
  width: 13em;
  /* text-align: center; */
  background-color: dodgerblue;
  padding: 1em;
  /* margin: 1em; */
}

.layoutexample {
  display: flex;
  color: black;
}

.layoutexample #examplenav {
  flex: 1;
  padding: 32px;
  background-color: lightblue;
  border-radius: 25px 0 0 25px;
}

.layoutexample article h2 {
  margin-top: 0;
}

#examplenav ul {
  text-align: right;
  list-style-type: none;
  margin: 0;
}

#examplenav li a {
  margin-bottom: 1em;
  display: inline-block;
  background: tomato;
  padding: 5px 10px;
  border-radius: 14px;
  color: white;
}

#examplenav li a:hover {
  background: indianred;
  padding: 5px 10px;
  border-radius: 14px;
  color: white;
}

.layoutexample article {
  flex: 5;
  padding: 32px;
  background-color: lavender;
  border-radius: 0 25px 25px 0;
}