20

I have an html list like this:

<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

How can I hide a li item and make it not occupy any space? Let's say, I need the first li item (coffee) to be invisible, so the result will contain only Tea and Milk. I used css (or style="visibility: hidden"), but it still occupies some space.

=======

Note: the first li is just some template used to create the other li items. The template li is generated during the run time, and that's why I need to hide it. I remove it eventually after generating the other li items (Tea and Milk), but before I generate Tea and Milk, Coffee is still visible.

============

Thanks. Answer is style="display:none"

Simo
  • 2,292
  • 5
  • 30
  • 45

6 Answers6

23

Create a class and apply it to elements which you wish to hide. You can do it when you generate markup or add the class to each element using a selector, like jquery

.hide{
  display:none;  
}
<ul>
  <li class="hide">Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>
Vu Nguyen
  • 543
  • 2
  • 12
3

In css you want (or some similar selector)

ul > li:first { display: none; }

Or if you prefer directly placing the css definition on the element itself

<ul>
 <li style="display:none;">Coffee</li>
 <li>Tea</li>
 <li>Milk</li>
</ul>

Another common practice is to simply create a style applied by a class if you wish to apply this style

<style> .nodisplay { display: none; } </style>
<ul>
 <li class="nodisplay">Coffee</li>
 <li>Tea</li>
 <li>Milk</li>
</ul>    

Using display:none; will remove the element from the flow of the page, and as a result there will be no blank space as can occur when using visibility: hidden;

"Turns off the display of an element (it has no effect on layout); all descendant elements also have their display turned off. The document is rendered as though the element did not exist.

To render an element box's dimensions, yet have its contents be invisible, see the visibility property." display: none MDN

Community
  • 1
  • 1
Travis J
  • 81,153
  • 41
  • 202
  • 273
2

Use display:none; instead.

That makes the element disappear and not take up any space.

HaukurHaf
  • 13,522
  • 5
  • 44
  • 59
2

You could style it.

...
<li style="display:none;">
....

That should hide the element

Coder-guy
  • 414
  • 6
  • 16
1

Just write this:

<ul class="groceries">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

.groceries {     
list-style: none;     
}    
Red Shark
  • 65
  • 1
  • 8
0

There are two ways you can achieve this. The first one is to use CSS display property :

Sample.html
<ul>
  <li class="list-hidden-item">Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>


Sample.css
.list-hidden-item { display: none; }

Another is to use HTML5 attribute hidden

Sample.html
<ul>
  <li hidden>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>
Rohan Shenoy
  • 805
  • 10
  • 23