Flexbox, Grid Layout and Media Queries: Advanced CSS Guide for Professional Web Designers

Flexbox and Grid Layout:

What is Flexbox?

Flexbox, or Flexible Box Layout, is a one-dimensional design model that allows the creation of flexible and efficient designs in a row or column. It's particularly useful when working with child elements of a container and looking for a design that dynamically adapts to the size of the screen or the content within it.

Here's an example of how to use the flexbox css:



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


In this example, display: flex; converts the container into a flexible container, and justify-content and Align-items control the distribution of child elements along the main and secondary axes, respectively.

In the following project you can see an example of how we could implement flexbox, to be able to align the images and even be able to work with media queries to achieve much more responsive images when viewing them on different screens, so as not to extend this topic too long, in the following link will be the complete project where you can see the code with some comments explaining the important points in flexbox:

As seen in the images, depending on the width of the screen, this is how they will be positioned, in the first case it is a width of 843 pixels, in the second of 558 pixels and in the third one 335 pixels.

https://github.com/karlacabanas01/flexbox

And what is Grid Layout? :

On the other hand, Grid Layout is a two-dimensional design system that allows the creation of grid structures. This approach is ideal when you want to organize elements in rows and columns, providing precise control over the location and size of the elements within the grid.

Example of Using Grid Layout:



.container {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  grid-gap: 20px;
}


In this example, display: grid; sets the container as a grid container, and grid-template-columns defines the columns of the grid with flexible proportions. Grid-gap add space between cells in the grid.

But which one is best suited to our project?

If we want to see which one to use or which one best suits what we require, we can see the following table to give us an idea:

What is CSS Grid?

👩🏻 ‍ 💻 Basic Concepts of CSS Grid

CSS Grid is a two-dimensional design system which allows you to control the arrangement of elements both in rows and in columns in a precise and flexible way.

For Activate CSS Grid, simply set display: grid in the container that you want to convert into a grid, Once the grid is activated, you can define the columns and rows utilizing grid-template-columns and grid-template-rows respectively. These properties allow you to specify the size and number of columns and rows, for example:



.container {
  display: grid;
  grid-template-columns: 100px 200px auto;
  grid-template-rows: 50px 100px;
}


Placing the elements on the Grid

It must be used grid-column and Grid-Row to position elements on the grid.

Grid Lines: Understand that elements can be placed and aligned using numbered grid lines or names.



.item {
  grid-column: 1 / 3;
  grid-row: 1;
}


Responsive Design

Use units Fr (Fractional Units) for adaptable columns and rows, use the function Repeat () to simplify the creation of multiple columns or rows, and use media queries to adjust the design to different screen sizes.



.container {
  grid-template-columns: repeat(3, 1fr);
}


Alignment and Justification

Align-items, justify-items, Align-content, and justify-content to align and justify the content inside the grid container and its cells.



.container {
  align-items: center;
  justify-items: center;
}


Grid Areas

It is used grid-template-areas to create a design based on area names, facilitating the placement of elements and to assign elements to specific areas it is used grid-area.



.container {
  grid-template-areas:
    "header header header"
    "main main sidebar"
    "footer footer footer";
}
.header { grid-area: header; }
.main { grid-area: main; }
.sidebar { grid-area: sidebar; }
.footer { grid-area: footer; }


👩🏻 ‍ 💻 Advanced Grids

Subgrid

The subgrid concept is an extension of the regular grid that allows child elements of a grid container to use the row and column definitions of the parent grid. This is especially useful in situations where you need to align the content of a nested grid component directly with the main grid.



.container {
  display: grid;
  grid-template-columns: 1fr 2fr;
}

.item {
  display: grid;
  grid-template-columns: subgrid; /* Las columnas del hijo corresponden a las del padre */
}


Function minmax ()

The function minmax () allows you to specify the minimum and maximum size of rows and columns. It is particularly useful for responsive designs, where dimensions must adapt to different screen sizes, but without exceeding certain limits.



.container {
  display: grid;
  grid-template-columns: repeat(3, minmax(100px, 1fr));
}


Spacing between elements with Gap

Formerly known as Grid-gap, the Gap (together with Row-Gap and Column-gap) allows you to define the space between rows and columns, facilitating design without affecting the padding or margins of individual elements.



.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px; /* Espacio entre filas y columnas */
}


Auto-fill vs. Auto-fit

These two functions are used with Repeat () to control how columns or rows are distributed in a grid container when the size of the container changes.

  • Auto-fill fill the container with as many cells of the specified size as possible, even if they are empty.
  • Auto-fit collapse the empty cells and expand the remaining cells to occupy the available space.


.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
}


Advanced Alignment and Overlay Control

CSS Grid offers detailed control over alignment with justify-self, Align-self, justify-items, Align-items, among others. In addition, you can superimpose elements in a controlled manner, intentionally placing them in the same cells of the grid.



.item1 {
  grid-column: 1 / 3;
  grid-row: 1;
}
.item2 {
  grid-column: 2 / 4;
  grid-row: 1;
}


Template-based design with grid-template-areas

This property allows you to create a design based on named areas, which greatly simplifies the design process, especially for complex designs.



.container {
  display: grid;
  grid-template-areas:
    "header header header"
    "main main sidebar"
    "footer footer footer";
}

.header { grid-area: header; }
.main { grid-area: main; }
.sidebar { grid-area: sidebar; }
.footer { grid-area: footer; }


📱 Media Queries and Responsive Design

As we mentioned in the previous post, media queries and responsive design in CSS are key concepts, allowing us to create websites that adapt to different devices and screen sizes.

Media Queries

They are a CSS feature that allows you to apply conditional styles based on the characteristics of the device or medium in which the page is being viewed.



/* Estilos para pantallas con un ancho máximo de 600px */
@media screen and (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}


Using Ranges and Logical Operators

Media queries aren't limited to fixed breakpoints. You can use ranges and logical operators (And, Not, Only, Or) to create more specific conditions. This allows you to fine-tune how and when certain styles are applied. For example:



@media (min-width: 600px) and (max-width: 900px) {
  body {
    background-color: blue;
  }
}


Combine Media Features

You can combine multiple features in a single media query to create very specific rules based on color, orientation, and other device factors:



@media (min-width: 600px) and (orientation: landscape) and (prefers-color-scheme: dark) {
  body {
    background-color: darkblue;
  }
}


Media Queries and CSS Grid

Integrating media queries with CSS Grid allows developers to redesign the layout of page elements in a more dynamic and adaptive way depending on the size of the device. For example, changing the number of columns in a grid based on the width of the viewport:



.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
}

@media (min-width: 800px) {
  .grid-container {
    grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  }
}


Optimizing Performance with Media Queries

Media queries can be used to optimize performance, loading resources only when necessary. For example, applying high-resolution background images only on large screens:



body {
  background-image: url('low-res.jpg');
}

@media (min-resolution: 2dppx) and (min-width: 1024px) {
  body {
    background-image: url('high-res.jpg');
  }
}


Mobile First

The Mobile First approach begins the design process with mobile devices and then expands to larger devices such as tablets and desktops. This method is especially beneficial for progressive web applications, where the mobile experience is a priority due to the high rate of devices such as cell phones.

Benefits of Mobile First:

  • Prioritization of content: When designing for mobile first, you're forced to focus on the most essential due to limited space, improving the user experience by reducing information overload.
  • Improved performance: Charging only the resources needed for mobile devices can reduce load times, which is crucial for maintaining user engagement on devices with less stable network connections.
  • Improved SEO: Google prioritizes mobile indexing, so a mobile-optimized design can contribute to a better ranking in search results.

Desktop First

Desktop First takes the opposite approach, starting with a design that fits large screens and then adjusts for smaller screens. This approach can be ideal for complex business applications or e-commerce platforms with robust functionalities that are initially designed to be used in a desktop environment.

Benefits of Desktop First:

  • Leveraging functionality: It allows designers to take full advantage of the features of the most powerful devices right from the start.
  • Flexibility in design: More screen space makes it easier to incorporate complex visual elements and advanced functionality.

Responsive Design:

It refers to the practice of designing and developing websites in ways that are fluidly adapted to different screen sizes and devices.

  • It is primarily used to ensure a consistent and optimal user experience regardless of whether the user is using a device with a large, medium or small screen, such as a desktop computer, tablet or mobile phone.
  • To achieve a responsive design, media queries are usually used together with relative units (such as percentages or units). In), flexible images and other CSS techniques.
  • A basic example of responsive design could be to adjust the text size and change the page layout to fit smaller screens, as shown in the following code:


body {
  font-size: 16px;
}

@media screen and (max-width: 600px) {
  body {
    font-size: 14px;
  }
}


Conclusion

In the world of web design, understanding and knowing how to implement Flexbox and Grid Layout together with Media Queries is essential for creating sites that not only look good on any device, but also work efficiently. Using strategies such as Mobile First and Desktop First helps us to ensure that our website is optimized for both mobile and desktop users, adapted to their specific needs.

These tools are especially valuable in areas such as progressive web applications and e-commerce platforms, where the user experience can vary greatly depending on the device used. For example, in a mobile application, speed is key, while in an online store, ease of navigation takes on greater importance.

🤯 Don't miss what's coming!In the next post, we're going to dive into the exciting world of CSS animations, transformations, transitions, pseudo-classes, and pseudo-elements. Let's explore how these advanced tools can give life and a special touch to your web projects, making them not only more interactive but also visually impressive.

Ready to take your web design skills to the next level?

At Kranio, we have experts in web development and design who will help you implement efficient solutions using Flexbox, Grid Layout and Media Queries, ensuring that your sites are responsive and optimized for all devices. Contact us and discover how we can promote the digital transformation of your company.

Karla Cabañas

September 16, 2024