115

I have the following div element:

.description {
  color: #b4afaf;
  font-size: 10px;
  font-weight: normal;
}
<div class="description">Some text here</div>

Then I have a click function on an element to hide the above div:

$('#target').click(function(){
  $(".description").hide();
});

When I hide the div, it collapses and stops taking up space. This messes up the layout of my page.

Is there a way to hide the div, but still maintain the space it was taking before? I don't want to change the font color because it would be still selectable.

Tot Zam
  • 8,406
  • 10
  • 51
  • 76
Y2theZ
  • 10,162
  • 38
  • 131
  • 200

6 Answers6

195

Use visibility css property for this

visibility:

The visibility property specifies whether the boxes generated by an element are rendered.

$(".description").css('visibility', 'hidden');

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
15

And another option for the sake of completeness. Toggle opacity:

$(".description").css('opacity', 0); // hide
$(".description").css('opacity', 1); // show

http://jsfiddle.net/KPqwt/

However using visibility is prefered for this task.

dfsq
  • 191,768
  • 25
  • 236
  • 258
13

Try:

$(".description").css("visibility", "hidden")

hide() is the equivalent to: $(".description").css("display", "none");

Which does not reserve the space the element was taking.

Hidden makes the element invisible, but stills reserves the space.

Darren
  • 68,902
  • 24
  • 138
  • 144
8

It's important to note that dfsq's example using Opacity:0 will still allow the contents to be selected, copy/pasted, etc., although there is no visible text-highlighting when selecting.

Community
  • 1
  • 1
fpscolin
  • 393
  • 3
  • 10
7

There are many ways to do that in CSS.

  • visibility: hidden; // preferred
  • transform: scale(0);
  • z-index: -999999; // not work with specific positioning
  • opacity: 0; // click and input events still work
wizawu
  • 1,881
  • 21
  • 33
3

you can wrap another div around the outside of it, and probably tell it a specific height to occupy. that way your inner div can show and hide and fadeOut, etc, and the outer div will hold down the real-estate on the page.

Heinz
  • 471
  • 4
  • 4
  • 2
    You could. But under what circumstances would you want to do this, when the accepted answer (from a year ago!) is simpler (no extra div needed), and does not require hard-coding a specific height? Even if you **wanted** a specific height, you wouldn't do this, you would just put the height in css on the already existing element. I don't mean to be rude, and I appreciate that it is good to have alternative solutions. I am just baffled by the suggestion of what appears to be an always-inferior solution, a year after the question was resolved? Am I missing something? – ToolmakerSteve Aug 11 '14 at 18:38