隐藏 div 但保留空白空间

我有以下 div 元素:

.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();
});

当我隐藏 div 时,它会收缩并停止占用空间,这会打乱页面的布局。

是否有办法隐藏 div,但仍然保持它之前占用的空间?我不想改变字体颜色,因为它仍然是可选的。

75405 次浏览

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

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.

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.

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.

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.

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