Создаем адаптивную страницу портфолио с фильтрами
Доброго времени суток уважаемые хабражители. На сегодняшний день уже многие знакомы с понятием адаптивный дизайн и я хочу поделиться интересной реализацией страницы портфолио с фильтрами.
HTML разметка
Указываем заголовок страницы, необходимые meta-теги, подключаем .css и .js файлы:
Создаем тело страницы. В блоке каждому элементу
Создаем элементы портфолио
Стилизуем основные элементы-контейнеры:
Задаем стиль для навигационной панели:
Стилизуем элементы портфолио:
Описание к каждой работе в портфолио должно появляться при наведении на нее (тег
Стилизуем классы .selected и .not-selected , свойства которых описывают изменения в анимации элементов
Selection и Scrollbar
Прошли те дни, когда было актуально стилизовать scrollbar в IE 5.5 и IE6 с помощью не стандартизированных W3C свойств вида scrollbar-base-color . Хочется поделиться одной интересной особенностью webkit:
C помощью псевдо-селекторов ::-webkit-scrollbar; ::-webkit-scrollbar-track; ::-webkit-scrollbar-thumb; мы простилизовали scrollbar в webkit, что похоже на скроллинг в Gmail. Учитывая количество пользователей Google Chrome, Safari, Yandex Browser мы можем смело применять эти свойства, так как это не останется незамеченным практически для половины аудитории Вашего сайта. Если я не ошибаюсь, то об этой полезности на хабре не рассказывалось, хотя данные префиксы поддерживаются с 2009 года. Подробно об этом пишет Cris Coyier на CSS Tricks.
Media Queries
965px или меньше
840 = (170+40)*4. Ширина .conteiner равна сумме ширины и значений свойств margin-left и margin-right помноженных на 4 (элемента).
860px или меньше
При этом разрешении в одной строке выводится три элемента — 720 = (200+40)*3.
740px или меньше
600 = (160+40)*3. Добавим непрозрачность 0.5 что бы на устройствах с данным разрешением заметнее выглядели элементы с классом .not-selected:
610px или меньше
480px или меньше
JavaScript — jQuery
Все просто — манипулируем классами:
- Создаем обработчик события при клике на категории nav > li
- У всех элементов, где класс совпадает с идентификатором выбранной категории удаляем класс .not-selected и добавляем .selected.
- Удаляем класс .corrent-li и добавляем .current-li выбранной категории.
- Для всех работ не входящих в выбранную категорию удаляем класс .selected и присваиваем .not-selected
UPD: Не нашел, где указать первоисточник в редакторе, напишу здесь — webdesign.tutsplus.com
UPD: Коллеги, все кто пишет о том, что тормозит — это последствия хабраэффекта.
Simple Filters in CSS or JS
In this post, I want to demonstrate how to add a simple and flexible filtering solution to a website. The use case here is that I have a collection of artifacts — in my case portfolio projects, but here we’ll simplify to animals — and I want to be able to:
- Filter by clicking a button (or div, etc.)
- Easily add new items to the collection without changing any code.
I will explore two different methods of applying the same filters to the same data, one based in JavaScript, the other based in CSS alone.
Let’s start by creating the html for the filters and the collection of animals, we’ll represent the filters as buttons and create a div for each animal:
Exit fullscreen mode
JS Filters — the more traditional way
There are, of course a lot of ways to filter using JavaScript. For this, I want to make sure that it’s flexible enough to cover anything I add in later because I don’t want to have to come back to edit the JS function. To do this I know that I’ll need a way to identify which animals to include/exclude for each filter, and I’ll want the HTML to do most of the heavy-lifting so I can add to the collection solely by adding HTML.
To start, I’ll add a class to each animal div with the name of the relevant filter(s). This will be my identifier.
Exit fullscreen mode
Notice that the last item, Salamander, can walk or swim. We’ll need to make sure that our filter function can handle items belonging to multiple criteria.
Next, I also know that I’ll need to add an event listener to each of the filters to call my JS function. Somehow, I want to pass the filter value to the function as well. We could write the event listener call like onclick=»filterAnimals(‘walks’)» but it might be nice to be able to grab the value of the filters in other code too, so let’s instead put the value as an HTML data- attribute and use that in our function instead. That has an added side effect of making the code a little more readable as well.
Exit fullscreen mode
Now it’s time to determine how to actually get the items to filter. In CSS, we can essentially remove an element from the page by setting it to display: none . Let’s create a class that has that setting, so our JS code can simply add/remove that class as needed. Well that was easy.
Exit fullscreen mode
JavaScript
What’s left to do? When we select a filter, our JavaScript only needs to go through the animals to see if they contain the filter as a class. If they do, they should not get the .hidden class, if they do not, then they do get that class added.
Exit fullscreen mode
Great! Now our filters should work, let’s take a look.
![]() |
![]() |
![]() |
![]() |
Notice our troublemaker Salamander does show up in both the walks and the swims filter, that’s great news! However, look at the all filter. not so good. We know there is data so surely there should be something there right? Unfortunately, we don’t have an .all class in any of our artifacts, so that filter won’t match anything. We could add .all to every animal, but it would be much cleaner and easier for our JavaScript to handle that. We just need an if/else statement to determine whether the filter is «all» or something more specific:
Exit fullscreen mode

There we go, now we’re all set. If we want to add something later, like an ostrich, we just need to put in a line of HTML:
<div >Ostrich</div>
Everything else is taken care of for us like magic.
CSS Filter
Let’s see how to implement the same thing, but without using any JavaScript at all. It involves a neat CSS trick!
First thing, we don’t need any event listeners anymore since there’s no JS functions to call, so let’s get rid of those. Otherwise everything is the same.
Exit fullscreen mode
But how can CSS actively filter for us? The key to that question is the «actively» part. When a user clicks a button, it is in focus until the user clicks elsewhere. So, we can use that to our advantage by adding a :focus selector to each button. We can also access our data- attributes using CSS to determine which filter to apply when a given button is in focus.
button[data-filter=»walks»]:focus
We also know we need the animals that are filtered out to receive the display: none attribute.
Exit fullscreen mode
But the challenge is how to actually select the animals, rather than the button, when we have the button in focus? We can use
to select «elements that follow an element at the same level.» This is officially called the «general-sibling-combinator» More Info Here.
The only issue is that this requires the animals and the filters to share a parent element, which they currently do not, so we’ll need to make a minor update to our HTML to make that happen by combining everything under a single div, let’s give it a .filteredList class.
With that change made, we can now use
to select «divs sharing the same parent as the selected button, whose class contains the data-filter attribute value from the button.» Here’s how that looks ( *= means ‘contains’ where = would require an exact match):
Exit fullscreen mode
JavaScript
There is no JavaScript — woohoo!
Full Code
Exit fullscreen mode
Now the moment of truth, does it work?
![]() |
![]() |
![]() |
![]() |
It Works!! Keep in mind that if you click anywhere else on the page, the filters will be removed (because the button is out of focus). And finally, how would we add our new ostrich animal? Exactly the same way:
<div >Ostrich</div>
Overall, the JavaScript function is probably going to be the better way to go in nearly all situations, but I thought this was a cool CSS trick and it could be useful if you want a lightweight quick-filter feature.
Product Filter and Search Using Javascript

Hey everyone. Welcome to today’s tutorial. In today’s tutorial, we will learn how to build a product filter and search. To create this project, we need HTML, CSS and Javascript. Since this is quite an advanced project, I wouldn’t recommend it for javascript beginners. If you are a javascript intermediate or expert you can surely go on and create this one.
Let us take an overview of what this project actually is. The project consists of a bunch of product cards. Each of these cards has a name, price and category assigned to them. Above these cards, there is a search bar where the user can search a product based on its name.
Below the search bar, there are a group of buttons. Each of these buttons has a category name on it. When the user clicks on any one of these buttons, the products corresponding to that particular category are shown.
Video Tutorial:
If you are interested to learn about this project by watching the video tutorial then do check out the video down below. Also be sure to subscribe to my youtube channel where I regularly post tutorials, tricks and tips.
Project Folder Structure:
Now let us first create the project folder structure so that we can begin the coding. We start by creating a project folder called – ‘Product Filter and Search’. Inside this folder, we create three files. The first is index.html , the second is style.css and the third is script.js . These files are the HTML document, the stylesheet and the script file respectively.
HTML:
We begin with the HTML code. Firstly copy the code below and paste it into your HTML file.
CSS:
Next to add styles to this project we use CSS. Now copy the code below and paste it into your CSS file.
Javascript:
Finally, we need to add functionality to the filter and also implement the search function. To make it working we add javascript. Do copy the code provided below and paste it into your javascript file.
Your product filter and search is now ready. I hope you liked the tutorial. If you have any issue regarding this code you can either download the source code or comment your doubts below. You can download the code by simply clicking on the download button below. If you have ideas, queries or suggestions do leave them in the comments below.
Happy Coding!
Создание компонента фильтра данных на чистом CSS

От автора: в этом руководстве мы узнаем о создании компонента фильтра данных на чистом CSS, для которого не требуется JavaScript. Мы будем использовать простую разметку, некоторые элементы управления формой и некоторые действительно интересные селекторы CSS, которые вы, возможно, раньше не использовали.
Над чем мы работаем
У каждого автора здесь на Tuts + есть собственная страница архива. Мы собираемся воссоздать такой список руководств, используя собственную разметку. Затем мы реализуем компонент, который будет фильтровать записи на основе категорий, к которым они принадлежат. Вот наш окончательный проект:
Давайте построим его!
1. Начинаем с HTML-разметки
Мы начнем с определения категорий фильтров в нашем компоненте. В этом примере мы будем использовать семь фильтров:

Профессия Frontend-разработчик PRO
Готовим Frontend-разработчиков с нуля
На курсе вы научитесь создавать интерфейсы веб-сервисов с помощью языков программирования и дополнительных технологий. Сможете разрабатывать планировщики задач, мессенджеры, интернет-магазины…
Для этого мы сначала определяем семь переключателей, которые группируем через ключевое словом categories. По умолчанию выбрана первая кнопка-переключатель:
Затем мы создаем упорядоченный список, который содержит метки, связанные с этими переключателями. Помните, что мы связываем переключатель с меткой, устанавливая его значение id равным значению for метки:
Затем мы настраиваем другой упорядоченный список, включающий элементы, которые мы хотим фильтровать (наши карточки). Каждый из отфильтрованных элементов будет иметь собственный атрибут data-category, значение которого представляет собой список фильтров, разделенных пробелами:
В нашем случае фильтруемые элементы будут постами. Таким образом, разметка, которую мы будем использовать для описания поста вместе с его мета-данными (заголовок, изображение, категории), выглядит следующим образом:
Когда разметка готова, давайте обратим внимание на необходимые стили.
2. Определение стилей
Сначала мы визуально скрываем переключатели:
Затем мы добавляем несколько стилей для фильтров:
CSS Grid Layout
Далее мы укажем некоторые стили для фильтруемых элементов. Самое главное, мы используем CSS Grid, чтобы уложить их по-разному в зависимости от размера экрана:
Примечание. Для удобства чтения мы не группируем в CSS общие правила.
Добавление стилей фильтрации
Идея здесь удивительно проста. Каждый раз, когда мы нажимаем на фильтр, должны отображаться только соответствующие отфильтрованные элементы (посты). Для реализации этого функционала мы будем использовать комбинацию следующих вещей:
Обратный псевдо-класс ( :not())
Общий комбинатор элементов одного уровня (
) переименованный в CSS4 в «последовательно-одноуровневый селектор»
Когда мы нажимаем на фильтр «All», отображаются все посты, имеющие атрибут data-category:
Когда мы нажимаем на любую другую категорию фильтра, будут видны только целевые посты:
Например, когда мы нажимаем на категорию фильтра «Slider «, будут отображаться только посты, принадлежащие этой категории.

Компонент фильтра на чистом CSS в действии
Стоит отметить, что в приведенных выше стилях вместо синтаксиса [att
=val] мы могли бы в равной степени использовать синтаксис [att*=val]. Вот как будет выглядеть это изменение:
Быстрое пояснение CSS-селектора
Что именно указывает этот селектор? Первая часть [value=»CSS»]:checked ищет выбранные переключатели с определенным значением (в данном случае «CSS»).
После этого тильда (
) — это то, что мы сейчас называем «последовательно-одноуровневым селектором». Он выбирает элементы, у которых тот же родительский элемент, что и у предыдущего элемента, даже если они в разметке расположены не рядом. Так что
.posts .post ищет элементы, .posts .post, у которых тот же родительский элемент, что и у выбранного переключателя.
Чтобы еще повысить специфичность, мы уточняем наш селектор :not([data-category
=»CSS»]), чтобы он выбирал только те элементы .post, у которых атрибут data-category не содержит значение «CSS» где-то внутри разделенного пробелами списка.
Затем он применяет display: none; к любым элементам, которые соответствуют этим критериям. Это довольно сложный селектор, хотя он вполне логичен. Человеческим языком вы можете описать это как: «Когда выбран переключатель со значением«CSS», найти все элементы, которые не содержат «CSS» в списке категорий данных, и скрыть их».
Завершающие стили
В качестве последнего шага мы добавим правило, которое выделяет активную категорию фильтра:



