Table of Contents
Creating a visually appealing and user-friendly photo portfolio is essential for photographers and artists. A flexible layout that adapts to different screen sizes and includes filtering options can greatly enhance the viewer’s experience. Using CSS Flexbox combined with simple JavaScript filtering, you can design a portfolio that is both attractive and functional.
Understanding Flexbox for Layout Design
Flexbox is a powerful CSS layout module that allows you to create flexible and responsive layouts with ease. It enables the arrangement of items in a row or column, with control over spacing, alignment, and order. For a photo portfolio, Flexbox can help organize images in a grid that adjusts to different screen sizes.
Setting Up the HTML Structure
Start by creating a container for your images. Each image should be wrapped in a div with a specific class to facilitate filtering. Additionally, include buttons for filtering options.
Here’s a simple example:
<div class="filter-buttons">
<button data-filter="all">All</button>
<button data-filter="nature">Nature</button>
<button data-filter="portrait">Portraits</button>
</div>
<div class="portfolio">
<div class="item nature"><img src="nature1.jpg" alt="Nature 1"></div>
<div class="item portrait"><img src="portrait1.jpg" alt="Portrait 1"></div>
<div class="item nature"><img src="nature2.jpg" alt="Nature 2"></div>
<div class="item portrait"><img src="portrait2.jpg" alt="Portrait 2"></div>
</div>
Applying Flexbox with CSS
Use CSS to style the portfolio container as a flex container. This will make the images align nicely and be responsive.
.portfolio {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.item {
flex: 1 1 calc(25% - 10px);
box-sizing: border-box;
}
.item img {
width: 100%;
height: auto;
display: block;
}
Implementing Filtering with JavaScript
To enable filtering, add JavaScript that responds to button clicks and shows or hides images based on their classes.
const buttons = document.querySelectorAll('.filter-buttons button');
const items = document.querySelectorAll('.portfolio .item');
buttons.forEach(button => {
button.addEventListener('click', () => {
const filter = button.getAttribute('data-filter');
items.forEach(item => {
if (filter === 'all' || item.classList.contains(filter)) {
item.style.display = 'block';
} else {
item.style.display = 'none';
}
});
});
});
Final Tips for a Responsive Portfolio
Adjust the flex-basis in the CSS to change the number of images per row on different screen sizes. Consider adding media queries for even better responsiveness.
Ensure your images are optimized for web to improve load times. Use descriptive alt text for accessibility. With these techniques, your photo portfolio will be both flexible and engaging for visitors.