Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
845 views
in Technique[技术] by (71.8m points)

css selectors - How to display the first 3 list items and hide the rest with CSS nth-child?

Is it possible to select multiple children past a defined number with CSS selectors?

I'd like to hide all list items past #3:

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li> <!-- hide this -->
  <li>5</li> <!-- hide this -->
</ul>

<style>
  ul li:nth-child(X) {
    display: none;
  }
</style>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I do not know which browser supports this, but you can pass a formula to :nth-of-type():

ul li:nth-of-type(1n+4) {display: none;} /* should match your case */

Further details on: http://www.w3schools.com/cssref/sel_nth-of-type.asp

Edit

I altered it from (n+4) to (1n+4) since the first version works but isn't valid. I use this in media queries to hide cut-down items on smaller screens.


Example:

b:nth-of-type(1n+4){ opacity:.3; }
<b>1</b>
<b>2</b>
<b>3</b>
<b>4</b>
<b>5</b>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...