I was wondering how to display only the first item in a list and make all the other items in the list hidden.
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
ul[id="list"] {
color: black;
display: none;
position: absolute;
font-size: 30px;
}
ul[id="list"]:nth-of-type(1) {
color: black;
display: block;
position: absolute;
font-size: 30px;
}
You're applying your CSS to the unordered list element rather than the items within that list.
One approach would be to combine the :not
and :first-child
pseudo-selectors to target all but the first list item.
#list li:not(:first-child) {
display: none;
}
Another option could be to use the adjacent sibling selector to again target all but the first item:
#list li + li {
display: none;
}
In the example you gave, you were using :nth-of-type(1)
. That too is a perfectly valid approach however it must applied to the list items and not the list itself. nth-of-type
is more common when you're expecting a variety of possible elements; in the case of a ul
the only possible child element is an li
. Typically you'd use :nth-child
but in your case, you want the first item therefore you'd opt for :first-child
instead. The end result is the same.
Are you expecting like this:
Note: first-child to work in IE8 and earlier versions
li{ display:none; } ul > :first-child { color:red; display:block; font-size: 30px; }
<body> <ul> <li>Coffee</li> <li>Tea</li> <li>Coca Cola</li> </ul> <ul> <li>Coffee</li> <li>Tea</li> <li>Coca Cola</li> </ul> <ul> <li>first element</li> <li>second element</li> <li>third element</li> </ul> </body>
ul[id="list"] li{ color: black; display: none; position: absolute; font-size: 30px; } ul[id="list"] li:first-of-type { color: black; display: block; position: absolute; font-size: 30px; }
<ul id="list"> <li>1</li> <li>2</li> <li>3</li> </ul>
:first-of-type selector in css allows you to target the first occurence of an element within its container.
Make li as target element so that you can get the result.
ul[id="list"] li{ color: black; display: none; position: absolute; font-size: 30px; } ul[id="list"] li:first-of-type { color: black; display: block; position: absolute; font-size: 30px; }
<ul id="list"> <li>1</li> <li>2</li> <li>3</li> </ul>
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.