Learn how to use Flexbox to create flexible, responsive layouts that adapt to different screen sizes.
Flexbox, or the Flexible Box Layout, is a CSS3 layout mode that provides an efficient way to lay out, align, and distribute space among items in a container. It adapts to various screen sizes, making it ideal for responsive design.
You need to create a website layout where items adjust automatically and maintain even spacing and alignment regardless of screen size. Traditional block model techniques can be cumbersome and less adaptable to various screen sizes. Flexbox offers a simpler, more dynamic solution.
Create a responsive product showcase where product cards adjust according to the screen size, ensuring accessibility and usability across devices. This layout should display product images, names, descriptions, and prices.
<div class="product-showcase">
<div class="product-card">
<img src="product1.jpg" alt="Product 1">
<h3>Product 1</h3>
<p>Description of Product 1</p>
<p>$19.99</p>
</div>
<div class="product-card">
<img src="product2.jpg" alt="Product 2">
<h3>Product 2</h3>
<p>Description of Product 2</p>
<p>$29.99</p>
</div>
<div class="product-card">
<img src="product3.jpg" alt="Product 3">
<h3>Product 3</h3>
<p>Description of Product 3</p>
<p>$39.99</p>
</div>
<!-- Add more product cards as needed -->
</div>
*{
box-sizing: border-box;
margin: 0;
padding: 0
}
/* Basic styles */
body {
font-family: Arial, sans-serif;
;
background-color: #f4f4f4;
}
.product-showcase {
display: flex;
flex-wrap: wrap;
gap: 20px;
padding: 20px;
justify-content: center;
}
.product-card {
display: flex;
flex-direction: column;
align-items: center;
width: calc(25% - 20px); /* 4 cards per row on large screens */
min-width: 200px;
padding: 20px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
background-color: #fff;
border-radius: 8px;
text-align: center;
transition: transform 0.3s;
}
.product-card:hover {
transform: translateY(-10px);
}
.product-card img {
max-width: 100%;
border-radius: 8px;
}
@media (max-width: 1200px) {
.product-card {
width: calc(33.333% - 20px); /* 3 cards per row on medium screens */
}
}
@media (max-width: 768px) {
.product-card {
width: calc(50% - 20px); /* 2 cards per row on small screens */
}
}
@media (max-width: 480px) {
.product-card {
width: 100%; /* 1 card per row on extra small screens */
}
}
.product-showcase
div is a flex container with flex-wrap: wrap
, allowing product cards to wrap to the next line.