Home > Enterprise >  i'm filtering divs without java and idk where to put the div on css
i'm filtering divs without java and idk where to put the div on css

Time:12-05

as you can see there's a div with an id named sidebar. idk what to put on css for it to work.

css:

button[data-filter="walks"]:focus ~ div div:not([class*="walks"]),
button[data-filter="swims"]:focus ~ div div:not([class*="swims"]),
button[data-filter="flies"]:focus ~ div div:not([class*="flies"]) {
  display:none;
}

html:

<div >
    <div id="sidebar">
       <h3>Filters</h3>
       <button  data-filter="*" tabindex="-1">All</button>
       <button  data-filter="walks" tabindex="-1">Walks</button> 
       <button  data-filter="swims" tabindex="-1">Swims</button> 
       <button  data-filter="flies" tabindex="-1">Flies</button>
    </div>
    
    <div id="animals">
       <h3>Animals</h3>
          <div >Dog</div>
          <div >Eagle</div>
          <div >Cow</div>
          <div >Shark</div>
          <div >Canary</div>
          <div >Human</div>
          <div >Salamander</div>
    </div>
</div>

i've tried using this:

#sidebar button[data-filter="walks"]:focus ~ div div:not([class*="walks"]),
#sidebar button[data-filter="swims"]:focus ~ div div:not([class*="swims"]),
#sidebar button[data-filter="flies"]:focus ~ div div:not([class*="flies"]) {
  display:none;

and i expected it to work.

CodePudding user response:

The issue is that CSS is always cascading.

You can't go up in structure, and CSS therefore expects the animals div to be a sibling of the buttons.

You'd need to restructure your HTML so that the filters are not nested inside the sidebar div for the snippet to work.

<div >
  <div id="sidebar">
    <h3>Filters</h3>
    <button  data-filter="*" tabindex="-1">All</button>
    <button  data-filter="walks" tabindex="-1">Walks</button> 
    <button  data-filter="swims" tabindex="-1">Swims</button> 
    <button  data-filter="flies" tabindex="-1">Flies</button>
    
    <div id="animals">
      <h3>Animals</h3>
      <div >Dog</div>
      <div >Eagle</div>
      <div >Cow</div>
      <div >Shark</div>
      <div >Canary</div>
      <div >Human</div>
      <div >Salamander</div>
    </div>
  </div>
</div>

With this change, your CSS code should work as expected and hide the div elements with the walks, swims, and flies class when the corresponding button element is focused.

Besides that, I'd recommend you to use checkboxes and ::checked for accessibility reasons.

CodePudding user response:

You can accomplish this with the new :has selector:

#sidebar:has(button[data-filter="walks"]:focus) ~ #animals div:not([class*="walks"]),
#sidebar:has(button[data-filter="swims"]:focus) ~ #animals div:not([class*="swims"]),
#sidebar:has(button[data-filter="flies"]:focus) ~ #animals div:not([class*="flies"]) {
    display:none;
}

Demo: https://jsfiddle.net/qy3wuv4b

  • Related