简体   繁体   中英

CSS hide style of sibling for element with specific ID

I am trying to hide sibling 1 and 2 that comes after an element with a specific ID I thought the code would look something like:

div[id*="pop_up"] + class{
  display: none !important; 
}

However, this does not seem to work, I am unsure how exactly I would use the sibling combination in this instance.

Your selector will only hide the first sibling having the specified class. If you want to remove the first and second sibling, you'll need something like the following:

 div[id*="pop_up"] +.hide-me, div[id*="pop_up"] +.hide-me +.hide-me { display: none;important; }
 <div id="pop_up1"></div> <p class="hide-me">Hide me!</p> <p class="hide-me">Hide me!</p>

Alternatively, you can use the General Sibling Selector, but that will cause all siblings with the specified class to be hidden. For example:

 div[id*="pop_up"] ~.hide-me { display: none;important; }
 <div id="pop_up1"></div> <p class="hide-me">Hide me!</p> <p class="hide-me">Hide me!</p> <p class="hide-me">Hide me!</p>

If you don't want to add selectors ad infinitum as shown in the first snippet, you can combine the ~ selector with nth-child as follows:

 div[id*="pop_up"] ~.hide-me:nth-child(-n+3) { display: none;important; }
 <div id="pop_up1"></div> <p class="hide-me">Hide me 1!</p> <p class="hide-me">Hide me 2!</p> <p class="hide-me">Hide me 3!</p> <p class="hide-me">Hide me 4!</p> <p class="hide-me">Hide me 5!</p>

I hope below is what you want.

 div#pop_up + *, div#pop_up + * + * { display: none; ;important; }
 <div id="pop_up"> Pop Up </div> <h1> sibling 1</h1> <p> sibling 2</p> <div> sibling 3</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM