Lesson 8: CSS Positioning, Display, and Flexbox

In this lesson, we will explore various CSS techniques to control the layout and positioning of elements on a web page.

Positioning

Positioning properties in CSS allow you to control the placement of elements on the page. The main positioning properties include:

  • static: Default positioning, element flows with the normal document flow
  • relative: Positioned relative to its normal position
  • absolute: Positioned relative to its nearest positioned ancestor
  • fixed: Positioned relative to the browser window
  • sticky: Positioned based on the user’s scroll position

Example:

.relative-box {
  position: relative;
  left: 20px;
  top: 10px;
}

.absolute-box {
  position: absolute;
  right: 30px;
  bottom: 40px;
}

.fixed-box {
  position: fixed;
  top: 0;
  right: 0;
}

Display

The display property in CSS defines how an element should be displayed on the page. Common display values include:

  • block: Displays an element as a block element, taking up the full width available
  • inline: Displays an element as an inline element, only taking up as much width as necessary
  • inline-block: Displays an element as an inline-level block container, allowing control over the width and height
  • none: Hides the element

Example:

.block-element {
  display: block;
}

.inline-element {
  display: inline;
}

.inline-block-element {
  display: inline-block;
  width: 200px;
  height: 50px;
}

Flexbox

Flexbox is a CSS layout model that allows you to create complex layouts with ease. Key flexbox properties include:

  • display: flex: Sets an element as a flex container
  • flex-direction: Sets the direction of the flex items (row or column)
  • justify-content: Aligns flex items along the main axis
  • align-items: Aligns flex items along the cross axis
  • flex-wrap: Allows flex items to wrap onto multiple lines
  • flex: Sets the flexible size of a flex item

Example:

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

.flex-item {
  flex: 1;
  margin: 10px;
}

Actionable Work

  1. Create an HTML file with a variety of elements that will demonstrate different positioning, display, and flexbox techniques.
  2. In a separate CSS file, apply various positioning properties to the elements.
  3. Use different display values to see how the elements behave on the page.
  4. Create a flex container with multiple flex items, and experiment with the flexbox properties.
  5. Link your CSS file to your HTML file and preview your work in a web browser to see the effects of positioning, display, and flexbox on the layout.