display first of class type

﹥>﹥吖頭↗ 提交于 2019-12-24 02:07:52

问题


I have a list of items, each with a class and the class are repeated throughout. I want to only show the first instance of each class. Is that possible with just CSS?

<ul>
   <li class="red">red</li>
   <li class="red">red</li>
   <li class="blue">blue</li>
   <li class="blue">blue</li>
   <li class="yellow">yellow</li>
   <li class="red">red</li>
   <li class="yellow">yellow</li>
</ul>
ul li {display:none}
ul li .red:first-child, ul li .blue:first-child, ul li .yellow:first-child { display:block}

So in the above code, only the 1st, 3rd & 5th list items should show.


回答1:


Use this code and add as many classes as you need.

.red,
.blue,
.yellow
{
    display: list-item;
}

.red ~ .red,
.blue ~ .blue,
.yellow ~ .yellow
{
    display: none;
}

Check this JSFiddle that uses your HTML and only displays the first elements of each class.

This is of course trivial if you have a predefined set of class names. In case your class names are unknown and/or there's an unmanageable amount of them they it would be best to resort to some scripting (using jQuery would help lots)




回答2:


In CSS2 you can use:

LI .red + .red { display: none; }
LI .blue + .blue { display: none; }
LI .yellow + .yellow { display: none; }

where + is the CSS2 adjacent selector

But I think it is not possible using a single rule for every color at once.




回答3:


For any items you want to hide, simply add a id to them.

<li class="red">red</li>
<li class="red" id="hide">red</li>

CSS:

#hide { display:none; }


来源:https://stackoverflow.com/questions/6407907/display-first-of-class-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!