Introduction To CSS Layout

Series

Goals

These articles will guide you through the essential layout tools and techniques offered by CSS. You will learn how to effectively structure and arrange elements on a webpage using: modern layout tools like flexbox and CSS grid, and some of the legacy techniques you might still want to know about

Target audience

This post is specifically for:

  • Have basic familiarity with HTML, if you don't checkout this post
  • Understand CSS fundamentals, as discussed in Introduction to CSS

CSS Layout

Normal flow

Normal flow refers to the default layout behavior of a browser when rendering HTML pages without any explicit layout instructions. In this context, elements are displayed one after another, vertically, in the order they appear in the HTML document.

Let's examine a simple HTML example to illustrate normal flow:

<h1>Welcome to Hytorium</h1>
<p>This is a paragraph of text.</p>
<img src="image.jpg" alt="Example image">
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
<p>Another paragraph of text.</p>
Demo normal flow

Welcome to Hytorium

This is a paragraph of text.

Example image
  • Item 1
  • Item 2
  • Item 3

Another paragraph of text.

The display property

The CSS display property is important for controlling how elements appear on a webpage. In fact, display is on of the most use property. It lets you choose the layout style for an element. By using different values for display, you can change how elements behave and create different layouts.

demo display property
item 1
item 2
item 3
item 4

In addition to changing the default appearance of elements from block to inline and vice versa, there are more advanced layout methods available using the display property. Two important values for layout are display: flex and display: grid.

When using these 2 layout, you can create more complex and flexible layouts. However, while provide powerful tools for arranging elements on a webpage, these values require additional properties to be set in order to achieve the desired layout.

Flexbox

Flexbox is a powerful and versatile tool for web developers that makes it easier to create responsive layouts. It allows us to easily manipulate the size, position, and order of elements on a web page, making it the perfect choice for creating complex layouts with minimal effort

Use display: flex

To use flexbox, we can apply display: flex to the parent element that contains the elements we want to arrange. This will make all its direct children become flex items, allowing us to control their layout using flexbox properties.

<div class="wrapper">  <!-- Flex container -->
  <div class="box1">One</div> <!-- Flex item -->
  <div class="box2">Two</div> <!-- Flex item -->
  <div class="box3">Three</div> <!-- Flex item -->
</div>
.wrapper {
  display: flex;
}
Demo Flexbox direction
One
Two
Three

Setting flex properties for flex items

In addition to properties for flex containers, there are specific properties for flex items. These properties control how items flex, allowing them to expand or contract based on available space. By applying these properties to individual items, you have more control over their behavior within the flex layout.

<div class="wrapper">  <!-- Flex container -->
  <div class="box1">One</div> <!-- Flex item -->
  <div class="box2">Two</div> <!-- Flex item -->
  <div class="box3">Three</div> <!-- Flex item -->
</div>
.wrapper {
  display: flex;
}
.wrapper > div {
  flex: 1;
}

The CSS rule flex: 1 applied to the child elements indicates that they should grow and shrink equally to fill the available space within the flex container. This is achieved by distributing the available space evenly among the flex items using the flex-grow and flex-shrink properties.

Demo Flexbox direction
item 1
item 2
item 3
item 4

Grid

CSS Grid Layout is a powerful tool for creating flexible and responsive layouts in CSS. It introduces a two-dimensional grid system that allows you to define columns and rows, and place elements onto the grid. By using the display: grid property on a container element, all its direct children become grid items.

Here's a simple example of using CSS Grid Layout:

<div class="wrapper">
  <div class="box1">One</div>
  <div class="box2">Two</div>
  <div class="box3">Three</div>
</div>
.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 100px 100px;
  gap: 10px;
}
 
.box1 {
  grid-column: 2 / 4;
  grid-row: 1;
}
 
.box2 {
  grid-column: 1;
  grid-row: 1 / 3;
}
 
.box3 {
  grid-row: 2;
  grid-column: 3;
}
Demo simple Grid layout
One
Two
Three

Floats

The float property in CSS allows you to position and format elements by floating them to the left or right side of their container. This property is commonly used to create layouts where text and inline elements wrap around a floated element.

When an element is floated, it is removed from the normal flow of the page but still remains a part of the flow. The computed value of the float property can be one of the following:

  • left: The element floats on the left side of its containing block.
  • right: The element floats on the right side of its containing block.
  • none: The element does not float and is displayed where it occurs in the text.
  • inline-start: The element floats on the start side of its containing block, which is the left side with left-to-right scripts and the right side with right-to-left scripts.
  • inline-end: The element floats on the end side of its containing block, which is the right side with left-to-right scripts and the left side with right-to-left scripts.

The float property can be applied to all elements, but it has no effect if the value of the display property is set to none. The default value is none, and the property is not inherited [1].

Common Use Cases of Float Property

The float property is commonly used in web design to achieve various layout effects. Here are some common use cases:

1. Wrapping text around images:

By floating an image to the left or right, you can make the text flow around it, creating a visually appealing layout.

img {
  float: left; /* or float: right; */
}
Demo Float Around Text
image

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aliquam minus reprehenderit, deleniti quasi nesciunt labore corporis, excepturi, necessitatibus consectetur aut et dolorem! Quos eligendi eveniet alias ducimus quasi veritatis harum!

2. Creating multi-column layouts:

Floats can be used to create multiple columns of content by floating block-level elements next to each other.

.column {
  float: left;
  width: 50%; /* Adjust the width as needed */
}
Demo Float Column
3. Clearing floats:

When floating elements, it's important to clear the floats to prevent layout issues. The clear property is used to specify whether an element should be positioned below the floating elements.

An element that has the clear property set on it will not move up adjacent to the float like the float desires, but will move itself down past the float.

Demo clear float
image 1
image 2

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nam corporis totam at magni quo praesentium sequi veritatis, voluptatum nulla iure fuga doloribus officia nobis delectus ea quos possimus ab reiciendis qui nihil. Cupiditate in enim architecto autem magni quae quia placeat nobis et incidunt doloribus hic temporibus neque ab commodi, esse optio deleniti odio itaque fugiat quisquam. Harum eaque dolores accusantium animi itaque voluptatem dolorum iusto facilis ea labore suscipit, beatae cumque?

.clearfix::after {
  content: "";
  display: table;
  clear: both;
}

The float property is a powerful tool for creating flexible and dynamic layouts in CSS. However, it's worth noting that with the advent of CSS Grid and Flexbox, the use of float for layout purposes has been largely replaced by these newer layout techniques.

Positioning

Positioning allows you to move an element from its normal position in the page layout to a different location. It's not used for creating the main structure of a page, but rather for managing and adjusting the position of specific items on the page.

However, positioning can be helpful in achieving specific layout patterns using the position property. It also helps in understanding how elements behave in the normal flow and how to move an item out of that flow.

There are five types of positioning you should know about:

  • Static positioning: This is the default position for every element. It means the element is placed in its normal position in the document flow without any special adjustments.

  • Relative positioning: With relative positioning, you can modify the position of an element on the page relative to its normal flow position. You can also make it overlap other elements on the page.

    Demo Position Relative
    normal flow element
    positioned element
    normal flow element
  • Absolute positioning: Absolute positioning removes an element from the normal layout flow and positions it relative to:

    • Its closest positioned ancestor
    • The <html> element if no other ancestors are positioned. This is useful for creating complex layout effects, like tabbed boxes or sliding information panels.
    Demo Position Absolute
    normal flow element
    positioned element
    normal flow element
  • Fixed positioning: Similar to absolute positioning, fixed positioning removes an element from the normal flow but positions it relative to the browser viewport. This is often used for creating elements like a navigation menu that remains in place while scrolling.

    Demo Position Fixed
  • Sticky positioning: Sticky positioning is a newer method that initially behaves like relative positioning. However, when the element reaches a defined offset from the viewport, it starts behaving like fixed positioning. It's commonly used for elements that stick to a specific position until a certain point.

    Demo Position Sticky

    Lorem ipsum dolor, sit amet consectetur adipisicing elit. Id cupiditate accusamus voluptas iste aut, et eos cumque blanditiis atque obcaecati aliquam nulla ipsam, mollitia voluptatum itaque tempore placeat ea vel?

    positioned element

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reiciendis suscipit optio minus autem totam possimus commodi aperiam dolorem cupiditate maiores, reprehenderit provident odio error sed non illum minima, blanditiis earum, nesciunt iure eveniet doloribus sapiente? Accusantium deleniti molestiae aut exercitationem aliquam aliquid ipsam dicta odio ullam dolore. Reiciendis nihil atque cumque unde qui recusandae corrupti sapiente doloribus ut, sequi hic molestiae officia deserunt. Cumque ut, in ad, aperiam quia voluptatum atque, ipsum consectetur excepturi recusandae possimus aut dignissimos tenetur odit vel magni accusantium facilis. Dolore, possimus deleniti vitae eligendi ducimus aut eius eveniet sit accusantium, fuga ipsa est et accusamus nobis quae! Officia dolores corporis adipisci dolor asperiores veritatis voluptates sequi? Rerum, nam saepe fugit ex culpa suscipit quibusdam nesciunt!

These different positioning techniques give you more control over the placement of elements on a web page, allowing you to create interesting layouts and effects.

Summary

This article has provided a brief summary of all the layout technologies you should know about. Read on for more information on each individual technology!