search
HomeWeb Front-endCSS TutorialUse pure CSS to implement filter menu function

In this article, we will use pure CSS to achieve the same effect as Taobao's baby filter menu. Although the example is not as powerful as Taobao, the principle is similar. If you put some effort, you can also achieve the same effect as Taobao. Hope it helps everyone.

Content filtering is a common function on the Web, especially on e-commerce websites. It allows users to filter content and only display content that meets their requirements. A screenshot can better illustrate this function, such as Taobao:


##

Use pure CSS to implement filter menu function



As shown in the picture above, the user wants to buy a dress. In the entire product list, there are too many products displayed. Customers don't know how to choose the dress they want. A category is provided at the top. Customers select the options they need, and the products that do not meet the conditions will be filtered out. In the picture above, I chose an "elegant" skirt. Of course, you can choose more conditions. I won’t say much more here.

Having said that, in the past, JavaScript (or jquery-based plug-in) was needed to achieve such an effect. For example, CodyHouse’s content filtering example. But for a student who doesn't understand JavaScript (not understanding is not a reason), it is indeed difficult to implement a similar function (sometimes I have personal experience and feel like crying without tears, who said I didn't study hard at the beginning).

Fortunately, puppets can now be implemented without JavaScript. In other words, it is not difficult to implement a content filter with simpler functions using pure CSS. This is what I want to share with you today.

Let’s look at an example first

Let’s look at a simple example first. When the page loads, women’s clothing, men’s clothing and children’s clothing will appear together. When you do the following During operation, there are unexpected effects:

When you click the "Women's Clothing" button, "Men's Clothing" and "Children's Clothing" will be filtered out

When you click the "Men's Clothing" button," Both "women's clothing" and "children's clothing" will be filtered out

When you click the "children's clothing" button, both "women's clothing" and "men's clothing" will be filtered out

Of course, the function of this case is not as good as Taobao It's so NB, but Haodai also implements a function similar to content filtering.


Implementation Principle
The principle of implementing this function is actually not too complicated, but everyone has not paid attention to it. I can summarize it in two aspects:


Powerful selector
To achieve this function, it mainly relies on the universal sibling selection in the powerful CSS selector Selector (E~F) and pseudo-class selector: checked. When a radio button is selected, the content of other categories is hidden:


input[type="radio"]{
    &[id="men"]:checked {
        ~ .women,
        ~ .children{
            ....
        }
    }
}

To control the corresponding .women and .children elements through the above style, you must ensure that the elements are consistent with the input element It’s the brotherly element. This is also the second key point to be discussed below.



Good, matching structure
Using only CSS to make this function requires a rigorous structure, because the disorder of the structure will directly affect the required effect. This is also its shortcoming. One of them is to use the radio button "radio" to match the label. In order to have a nice appearance, if you do not want to display , you need to control the selected "radio" through the for attribute of the label. Therefore, the id value of the input must match the for value of the label. In addition, the name values ​​of all inputs are the same, telling the browser that they belong to a group. For example:


<input type="radio" id="men" name="clothing" />
<label for="men">男装</label>
<input type="radio" id="women" name="clothing"/>
<label for="women">女装</label>
<input type="radio" id="children" name="clothing"/>
<label for="children">童装</label>
<input type="radio" id="reset" name="clothing"/>
<label for="reset">重置</label>

Implementation steps
After understanding the implementation principle, it will be much simpler to complete the effect of the example at the beginning of the article.

HTML

The HTML structure is actually very simple. You only need to pay attention to the matching of input and label and the content element to be filtered and its sibling element. For example, in this example, there are three main categories of content elements: men's clothing.men, women's clothing.women and children's clothing.children.


<p class="container">
    <!-- 必须保证input和label匹配 -->
    <input type="radio" id="men" name="clothing " />
    <label for="men">男装</label>
    <input type="radio" id="women" name="clothing "/>
    <label for="women">女装</label>
    <input type="radio" id="children" name="clothing "/>
    <label for="children">童装</label>
    <input type="radio" id="reset" name="clothing "/>
    <label for="reset">重置</label>
    <!-- 要被过滤的内容元素需要与input元素是兄弟元素 -->
    <p class="tile men">
        <img src="/static/imghwm/default1.png"  data-src="" alt="  class="lazy"   alt="">
    </p>
    <p class="tile women">
        <img src="/static/imghwm/default1.png"  data-src="" alt="  class="lazy"   alt="">
    </p>
    <p class="tile children">
        <img src="/static/imghwm/default1.png"  data-src="" alt="  class="lazy"   alt="">
    </p>
    <!-- 此处省略N个.men、.women和.children元素 -->
</p>

SCSS


It’s much simpler if you understand the principle. Let’s first look at the overall code:


body{
  margin:0;
  text-align:center;
  font-family: Verdana;
  background:#f5f5f5;
}
h1 {
  text-align:center;
}
.container {
  width:90%;
  margin:0 auto;
}
input[type="radio"] {
  display:none;
}
label {
  width:23%;
  float:left;
  text-align:center;
  background:#ffffff;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
  color:#222222;
  padding:0.5%;
  margin:0.5%;
  margin-bottom:30px;
  cursor:pointer;
}
input[type="radio"]{
  &[id="men"]:checked {
    * label {
      background:#6666ff;
    }
    ~ .women,
    ~ .children {
      width:0;
      height:0;
      padding:0;
      margin:0;
      opacity:0;
    }
  }
  &[id="women"]:checked {
    * label {
      background:#ff4466;
    }
    ~ .men,
    ~ .children {
      width:0;
      height:0;
      padding:0;
      margin:0;
      opacity:0;
    }
  }
  &[id="children"]:checked {
    * label {
      background:#66dd99;
    }
    ~ .men, 
    ~ .women {
      width:0;
      height:0;
      padding:0;
      margin:0;
      opacity:0;
    }
  }
}
.tile {
  width:23%;
  float:left;
  transition:all 1s;
  margin:0.5%;
  padding:0.5%;
  background:#6666ff;
  img {
      width: 100%;
    }
}

Simple Analyze this style code.


In order to make the page look better, first hide the :


input[type="radio"] {
  display:none;
}

We use the for attribute of the label to control whether the radio is selected. Beautify the label style:



label {
    width:23%;
    float:left;
    text-align:center;
    background:#ffffff;
    box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
    color:#222222;
    padding:0.5%;
    margin:0.5%;
    margin-bottom:30px;
    cursor:pointer;
}

The next style code is also the most critical part. When the input is selected, the label style:



input[type="radio"]{
  &[id="men"]:checked {
      label {
      background:#6666ff;
    }
  }
  ...
}

Above The code represents when selected: checked, its adjacent label changes the background color.


According to the previous principle introduction, we can know that when we choose "Men's Clothing", then "Women's Clothing" and "Children's Clothing" need to be hidden. Here they are hidden through false images, that is, input[type= "radio"][id="men"] is selected, and its similar sibling elements .women and .children are hidden:


input[type="radio"]{
  &[id="men"]:checked {
    ...
    ~ .women,
    ~ .children {
      width:0;
      height:0;
      padding:0;
      margin:0;
      opacity:0;
    }
  }
}

其他两个选项也是类似的,就不在做过多的阐述。

美化的样式,这里就不说了,大家都懂的。

通过这个过程下来,你就能看到前面DEMO展示的效果了。
总结

本文主要介绍了如何依赖于CSS的属性选择器、通用相邻兄弟选择器和伪类选择器来实现一个简单的Use pure CSS to implement filter menu function的功能。在整个实例当中,要把握的是严谨的HTML结构,因为相邻兄弟选择器对于结构的依赖程度非常的强。也就是说结构修改之后,你的选择器和样式都要做一定的修改。
相关推荐:

最简洁的CSS学习笔记

全面总结css中属性值继承知识

css和js实现弹出登录居中界面教程

The above is the detailed content of Use pure CSS to implement filter menu function. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
So Many Color LinksSo Many Color LinksApr 13, 2025 am 11:36 AM

There's been a run of tools, articles, and resources about color lately. Please allow me to close a few tabs by rounding them up here for your enjoyment.

How Auto Margins Work in FlexboxHow Auto Margins Work in FlexboxApr 13, 2025 am 11:35 AM

Robin has covered this before, but I've heard some confusion about it in the past few weeks and saw another person take a stab at explaining it, and I wanted

Moving Rainbow UnderlinesMoving Rainbow UnderlinesApr 13, 2025 am 11:27 AM

I absolutely love the design of the Sandwich site. Among many beautiful features are these headlines with rainbow underlines that move as you scroll. It's not

New Year, New Job? Let's Make a Grid-Powered Resume!New Year, New Job? Let's Make a Grid-Powered Resume!Apr 13, 2025 am 11:26 AM

Many popular resume designs are making the most of the available page space by laying sections out in a grid shape. Let’s use CSS Grid to create a layout that

One Way to Break Users Out of the Habit of Reloading Too MuchOne Way to Break Users Out of the Habit of Reloading Too MuchApr 13, 2025 am 11:25 AM

Page reloads are a thing. Sometimes we refresh a page when we think it’s unresponsive, or believe that new content is available. Sometimes we’re just mad at

Domain-Driven Design With ReactDomain-Driven Design With ReactApr 13, 2025 am 11:22 AM

There is very little guidance on how to organize front-end applications in the world of React. (Just move files around until it “feels right,” lol). The truth

Detecting Inactive UsersDetecting Inactive UsersApr 13, 2025 am 11:08 AM

Most of the time you don’t really care about whether a user is actively engaged or temporarily inactive on your application. Inactive, meaning, perhaps they

Wufoo   ZapierWufoo ZapierApr 13, 2025 am 11:02 AM

Wufoo has always been great with integrations. They have integrations with specific apps, like Campaign Monitor, Mailchimp, and Typekit, but they also

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.