Photo by Goran Ivos / Unsplash

Flexbox Introduction

Html & Css For Beginners Mar 9, 2023

Layout Options in CSS Overview

Jen runs through a few slides describing layout options in CSS.

Slide PDF

Flexbox intro to basic properties

Jen demonstrates the basic Flexbox properties as described below.

Starting CodePen

Flexbox Properties.txt is a useful document to have nearby when working in Flexbox. It explains which properties apply to parents and children, along with most of their possible values.

You may also refer to CSS Tricks Guide to Flexbox.

Flexbox Explained

For each of the directions below, add these declarations to the existing ul or li elements.

The first grouping has to do with the flex-container, or the ul in this example.

  1. ul { display: flex; } This gets everything on a single line. By default, the direction is in a row and in standard order.
  2. ul {display: flex; flex-direction: X; } X = row, row-reverse, column, column-reverse This takes the elements and places them in a single row or a single column. Ordering is either in source order or the reverse of the source order. Flex-direction defines our main axis.
  3. ul { display: flex; flex-direction: as before, flex-wrap: X;} X = wrap, wrap-reverse, or nowrap flex-direction orders the individual items. flex-wrap orders the rows/columns created.
  4. ul { display: flex; flex-flow: X;} flex-flow is shorthand for flex-direction and flex-wrap It takes two arguments, just like the individual properties. Example: row wrap, row-reverse wrap, column nowrap, column-reverse wrap-reverse, etc Just because the row/column is reversed does not mean the wrap has to be reversed
  5. ul { display: flex; flex-flow: row wrap; justify-content: X; } X = flex-start, flex-end, center, space-between, space-around, space-evenly justify-content determines the distribution of the flex items within the flex container on the main axis — in other words, how should space be allocated relative to the width of each item? If flex direction is row, then horizontal is the main axis. When flex-direction is column, then column is the main axis.
  6. ul { display: flex; flex-flow: row wrap; justify-content: center; align-items: X} X = flex-start, flex-end, center, baseline, stretch This aligns our items on the cross axis. Since we’re working with a row currently, this is aligning elements in vertical space.
  7. ul { display: flex; flex-flow: row wrap; justify-content: center; align-items: center; align-content: X} *X = flex-start, flex-end, center, space-between, space-around, space-evenly Notice that changing align-content further aligns all boxes to the center of the ul. Without this, the boxes are distributed with space-around by default.

The next set of properties are about the individual flex-items, or the li’s in this example.

  1. .flex2{ border: 2px dotted blue; order: X; } X can be an integer. 1 will move the .flex2 boxes to the end of the list, while -1 will move them to the start of the list. 0 is neutral.
  2. .flex2{ border: 2px dotted blue; flex-basis: X; } flex-basis is analogous to width, but not quite the same thing. Width is an absolute measurement — an element is that wide, all the time. We can measure width in relative units (say 25% instead of 250px), but in the end, the measurement itself never changes. For flex-basis, we try to achieve a given width with the space available. It could be smaller than this width, or it could be wider, depending on the extra space and how that’s supposed to be distributed. Distribution of extra space is controlled by flex-grow and flex-shrink (below).
  3. .flex2{ border: 2px dotted blue; flex-grow: X; } X can be 0 or a positive integer. (It won’t break with a negative integer, but it won’t do anything either.) flex-grow, like flex-shrink (below), distributes extra space once each element is displayed on the page. In this example, our flex items are center-aligned (see justify-content: center on the ul). By assigning a value to flex-grow, any extra space will be assigned in greater proportion to this element, making it larger relative to the other items. Note there is no unit with this measurement — it’s simply a proportion.
  4. .flex2{ border: 2px dotted blue; flex-shrink: X; } X can be 0 or a positive integer. (It won’t break with a negative integer, but it won’t do anything either.) flex-shrink controls what happens to extra space as elements shrink. By assigning a value to flex-shrink, as elements get smaller on the page, this element will get smaller faster than the others. Note there is no unit with this measurement — it’s simply a proportion.
  5. .flex2{ border: 2px dotted blue; flex: G S B; } G = flex-grow S = flex-shrink B = flex-basis This is the shorthand for combining flex-grow, flex-shrink, and flex-basis.


Flexbox Grid System

Part 2A: Desktop Only

Starting CodePen

Finished CodePen

Next, we'll create a 4-column grid system.

We'll also write some code for reversing the rows and reordering boxes within a row.

Part 2B: Responsive System

Now we'll add media queries to make our grid system mobile-first.

Starting CodePen (continues from the 2A finished state)

Finished CodePen

Part 2C: You Try It

Use the starting CodePen to code the layout as described.

Starting CodePen

Finished CodePen

Math Notes

When approaching this problem, it's helpful to make the following adjustments.

A. Make sure you are working with the border box model, not the content box model.

Border vs content box explained

CSS to set the border box model - place at the top of your CSS file (or early in your CSS stack):

html { box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; }

B. When constructing a grid of X columns, go through the following steps at EACH breakpoint and adjust flex-basis accordingly.

  1. How many columns will you have at a maximum? In our example, it's 4 columns.
  2. Draw a sketch with one box per column with a space in between.
  3. Consider the width of the gap you'd like. Use % as your width. In our example, we had 3 gaps, and we used 4% width for each gap.
  4. 100% - (3 gaps * 4%) = 88% left over for our 4 boxes.
  5. 88% / 4 = 22% per box. Set the flex-basis to 22% for this size of box.
  6. When combining boxes, figure the new box size over the columns and add in the gap(s).

| Box 1 |    | Box 2 | 22% + 4% +  22%  = 48% | Box 1 |    | Box 2 |    | Box 3 | 22% + 4% +  22%  + 4% + 22% = 74%

  1. Now write classes for the sizes you need.

PRO TIP: It's possible to tighten up the CSS even further with CSS variables and calc(). I cover this in "Advanced CSS Layouts."

NOTE: There is a new gap property in Flexbox as well, described on MDN.

You will get slightly different results using gap rather than the method described above. Here, the gap will be preserved longer and boxes will wrap to the next line sooner than they will without a specific gap declared.

You may combine both methods without difficulty.

Figure Caption & Figure Caption with Flexbox


Chapter 3: figure and figcaption

Starting CodePen

Ending CodePen

Flexbox may be applied to as many elements in the document as you wish. Remember to always manage parents (flex containers) and children (flex items) appropriately.

In this case, if we declare display: flex on the figure, then the caption may be placed next to the image (row) or underneath it (column) very easily.

Use relative and absolute positioning to move the caption onto the image. Change the color to include some transparency, or use the opacity property to manipulate the transparency.

Changed CSS:figure { display: flex; flex-flow: column nowrap; position: relative; } figcaption { position: absolute; bottom: 0%; width: 100%; opacity: 0.7; }


Flexbox Exercises

We'll complete three parts to this exercise, depending on time.

Part 4A: Collections

This is the first section of a larger page we'll code over the course of today.

Refer to desktop.png, tablet.png, and mobile.png for the look we want with this page.

In the starting "begin" folder, you'll find HTML and CSS to get you started.

Jen inserted only 6 classes, one per <figure> element, to completely style this document. No additional classes should be necessary to style the page. (Practice your selectors!)

Part 4B: Mission

You're given a logo and text for a mission section of the page. Lay this out in some way across the breakpoints.

I've provided two suggestions -- the suggestion I'll use going forward (using a float and CSS shapes) and an alternative (using Flexbox). There are screenshots for all breakpoints for you to look at.

Suggested approach

Logo.png is the standard PNG logo file, cropped closely around the logo itself. This is useful if you put the image in one Flexbox cell and the text in another, which is my alternative approach.

Logo2.png has a wider background. You may want to use this if you'd like to experiment with CSS shapes. For example, make the text follow the diagonal slant of the logo side.

If you take the approach with CSS shapes, you will need to float the image rather than placing it in its own Flexbox cell. Remember to clear your float!

Shape suggestion

a. Visit MDN and copy the shape-outside code for a polygon:

shape-outside: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);

b. Apply that to your image in the CSS and save.

c. Open the page in Firefox (NOT CHROME) and use the devtools to manipulate the points on the shape to where you want them. (This feature is not available in Chrome.)

d. Copy the finalized shape-outside CSS declaration and paste to your CSS document.

Lay out the footer with the markup given. I've given you two SVGs for social media images; feel free to add more if you wish. You may link these to the home pages for the social media sites or to your own pages.

You may need to modify the HTML slightly to make this layout work.

I've provided screenshots for how I did this.

Flexbox Header and Navbar


Let's move on to laying out the header of the web page. We can do this with one navigation bar that includes the logo. By using Flexbox to lay out the navbar, we can then move the logo around wherever we want it -- far left and inline with the navbar, in the center of the navigation, or on its own line, separate from the rest of the navigation.

Responsive Images


A. Presentation on responsive images: <picture>, srcset, sizes, responsive background images.

B. Jen will demonstrate ResponsiveBreakpoints.com, which generates a suite of images and srcset/sizes code to use on your page.

She will also demonstrate the banner demo inside the site.

REMEMBER: <picture> means YOU decide which image displays when. srcset/sizes means the BROWSER decides - and it doesn't always decide what you think it should!

C. To our page, add a "featured print" and a "hero banner" section of the web page using the starting graphic and the screenshots provided.

Starting graphics include hero.png and too-cool.jpg. You will need to create additional versions of these images and write the code to include them in the site.

SUGGESTED: Use <picture> for the hero banner and srcset/sizes for the featured print.

Flexbox Wrapup


a. Add a "popular prints" section of the web page, just after "our mission". See the screenshots for how this should look. Captions for the photos include:

  • Fork It Up (the fork)
  • Eyeing You (the car)
  • Let's Scoot (the vespa scooter)

b. If you have time, clean up the formatting, comments, spacing and alignment, etc, to make it portfolio-worthy!


Tags

Error to 200

Error to 200 means "Error to Success Status". Through this blog and youtube channel, I attempt to teach basics and those coding techniques to people in a short time, which took me ages to learn.