Looking at the answers, the big problem is that using only opacity: 0
, a lot of things escapes, because the element is not visible, but it is still there, that is, it remains selectable, "clickable", occupying the space and doing everything it would do without opacity, simply interacting with the "invisible" area".
To solve this problem is very simple, just along with the opacity: 0
, include pointer-events: none; user-select: none; z-index: -1
.
Example I:
Without changing the element size
const span = document.querySelector('span');
const button = document.querySelector('button');
const exemplo = () => span.classList.toggle('transition');
button.addEventListener('click', exemplo);
/* Estado padrão */
span {
-webkit-transition: opacity 500ms;
-o-transition: opacity 500ms;
transition: opacity 500ms;
/* IGNORE */
display: block;
}
.transition {
pointer-events: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
z-index: -1;
opacity: 0;
}
/* IGNORE */
div {
border: 1px solid black;
padding: 10px;
text-align: center;
}
<div>
<span>Sem modificar o tamanho do elemento</span>
<button>Testar</button>
</div>
When you want the spacing also to be corrected by hiding the element and, also with the transition, you can put a height
static using only CSS or dynamic, with JS.
Example II:
Changing the size of the element
const span = document.querySelector('span');
const span_height = span.clientHeight;
const button = document.querySelector('button');
const exemplo = () => {
span.classList.toggle('transition');
span.style.height = !span.classList.contains('transition') ? `${span_height}px` : 0;
}
span.style.height = `${span_height}px`; // garante a transição na primeira chamada
button.addEventListener('click', exemplo);
/* Estado padrão */
span {
-webkit-transition: opacity 400ms, height 500ms;
-o-transition: opacity 400ms, height 500ms;
transition: opacity 400ms, height 500ms;
/* IGNORE */
display: block;
}
.transition {
pointer-events: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
opacity: 0;
z-index: -1;
overflow: hidden;
}
/* IGNORE */
div {
border: 1px solid black;
padding: 10px;
text-align: center;
}
<div>
<span>Modificando o tamanho do elemento</span>
<button>Testar</button>
</div>
- Note that in neither of the two examples, it is possible to interact with the elements while hidden.
Your problem is that you used display, and display has no middle ground, either is or is not on screen. Vc can replace by display by opacity which should work
– hugocsl