Make DIV invisible in CSS and JavaScript

Aram Kocharyan picture Aram Kocharyan · Feb 25, 2011 · Viewed 90.4k times · Source

I have managed to make a DIV tag invisible in JavaScript by setting the display to none and the visibility to hidden. It can be achieved with this class also:

.invisible {
    display: none;
    visibility: hidden;
}

Display none will ensure the DIV box is empty, and visibility hidden will ensure it isn't visible. The problem with this method is when I have scrollable DIVs or textareas with overflowing content, when you set display: none, some browsers will forget the scroll position for these elements. Is there a better way to make a DIV invisible without using the display property? I would rather not resort to using JavaScript to record the scroll position and such if possible.

EDIT:

I managed to solve it with your help, I applied the following:

.invisible {
    visibility: hidden;
    position: absolute;
    top: -9999px;
}

.visible {
    visibility: visible;
    position: static;
}

I tried left: -9999px, but this expands the vertical scrollbar in IE... I also wrapped my textarea in another DIV and applied the visible/invisible styles to that, because the textarea would lose its scroll position otherwise. I tested this in Chrome, Firefox, IE and Safari on my iPhone. Just a note, the DIV wrapped around the textarea didn't seem to help in FF, and the scrollbar still reset. But the scrollable DIVs are fine now. Thanks for your help!

Answer

Chris Van Opstal picture Chris Van Opstal · Feb 25, 2011

You can just use visibility:hidden if you want the element to be invisible but still rendered. display:none will remove it entirely and cause the scroll behavior you mentioned.