Welcome to the CSS Flexbox Responsive lesson! In this tutorial, we'll dive deep into understanding Flexbox, a powerful layout module in CSS that simplifies web design, making it more responsive and adaptable to various screen sizes.
Flexbox, short for Flexible Box Layout, is a one-dimensional or two-dimensional layout model that provides a more intuitive way to design and align UI elements on a webpage. Flexbox allows you to create flexible and responsive layouts with ease.
To start using Flexbox, first, you need to include the CSS reset in your HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>CSS Flexbox Responsive</title>
</head>
<body>
<!-- Your HTML content here -->
</body>
</html>Now, let's create a basic Flexbox example:
/* Add the following CSS in your styles.css file */
.flex-container {
display: flex; /* This makes the container a flex container */
justify-content: space-between; /* This ensures the items are spaced evenly */
width: 100%;
}
.flex-item {
background-color: #ddd; /* Adds some color to our items */
margin: 10px; /* Adds some space between items */
width: 150px; /* Sets the width of each item */
height: 150px; /* Sets the height of each item */
}In your HTML, create a container and some items:
<div class="flex-container">
<div class="flex-item"></div>
<div class="flex-item"></div>
<div class="flex-item"></div>
</div>display: flexThis property turns the element into a flex container.
justify-contentThis property defines the alignment along the main axis.
align-itemsThis property defines the alignment along the cross axis.
flex-directionThis property sets the direction (row or column) of the flex items.
flex-wrapThis property determines whether the flex container should wrap the items when there is no space.
Let's create a practical example of a responsive image gallery using Flexbox:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>CSS Flexbox Responsive</title>
</head>
<body>
<div class="gallery" id="gallery">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<!-- Add more images as needed -->
</div>
<script src="script.js"></script>
</body>
</html>In your CSS file, apply Flexbox styles to the gallery:
/* Add the following CSS in your styles.css file */
.gallery {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
width: 100%;
}
.gallery img {
width: 31%;
height: auto;
margin: 1%;
}What property is used to set the direction (row or column) of the flex items?
Stay tuned for more on CSS Flexbox Responsive! In the next part, we'll dive deeper into advanced Flexbox properties and real-world examples. 🎯