Responsive Design with Flexbox and CSS Grid



Responsive Design with Flexbox and CSS Grid body { font-family: sans-serif; margin: 0; padding: 0; } header { background-color: #f0f0f0; padding: 20px; text-align: center; } h1 { color: #333; } main { padding: 20px; } section { margin-bottom: 40px; } h2 { color: #007bff; } p { line-height: 1.6; } code { background-color: #222; color: #fff; padding: 10px; display: block; margin-top: 10px; margin-bottom: 10px; font-family: monospace; } .highlight { background-color: #ffffe0; padding: 5px; border-radius: 5px; } .flex-container { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; } .flex-item { width: 48%; margin-bottom: 20px; } @media (max-width: 768px) { .flex-item { width: 100%; } } .grid-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; } .grid-item { background-color: #f5f5f5; padding: 20px; border-radius: 5px; }

Responsive Design with Flexbox and CSS Grid

Introduction

In today's digital world, it is essential for websites to be responsive and adapt to different screen sizes. This means that your website should look good and function properly on desktops, laptops, tablets, and smartphones. Flexbox and CSS Grid are two powerful tools that can help you create responsive layouts with ease.

Flexbox

Flexbox is a one-dimensional layout model that allows you to align and distribute items within a container. It is great for creating flexible and responsive layouts for rows and columns. Here is an example of using Flexbox:

.flex-container { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; } .flex-item { width: 48%; margin-bottom: 20px; } @media (max-width: 768px) { .flex-item { width: 100%; } }

This code creates a flex container that will automatically adjust the width of its items based on the screen size. The @media query ensures that the items will take up the full width on smaller screens.

CSS Grid

CSS Grid is a two-dimensional layout model that provides more control over the placement and sizing of items. It is ideal for creating complex and responsive layouts, such as dashboards and landing pages. Here is an example of using CSS Grid:

.grid-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; } .grid-item { background-color: #f5f5f5; padding: 20px; border-radius: 5px; }

This code creates a grid container with a flexible number of columns that will adjust based on the screen size. The gap property ensures that there is space between the grid items.

Conclusion

Flexbox and CSS Grid are essential tools for creating responsive and engaging web experiences. By mastering these techniques, you can ensure that your website looks great and functions seamlessly on all devices.