Search code examples
cssheighthidden

Force a parent's height with hidden child element in CSS


If I have a hidden child element (with either display: none or visibility: hidden), how can I have the parent div keeps it's height so that when the child is made visible, the parent height does not change?

Do I need to set an absolute height on the parent or can I still have it calculate its height from the child?


Solution

  • display:none removes the element from the flow, so no way to make the parent keept the height (other than hard-coding a fixed value). It should also hide it from screen readers and crawlers.

    visiblity:hidden keeps the element in the flow, and therefore, keeps the space reserved for it, so the parent will keep the height just as if the element was visible.

    opacity:0 will also act just like visibility:hidden, while allowing the reveal of the element to be transitioned / animated to opacity:1.

    So you should use either visibility:hidden or opacity:0, depending on if you want to show the element in a jumpy reveal or transition.

    Edit:

    It should also be noted that visibility:hidden will not fire events (such as a click, hover, etc) while opacity:0 will. So there are even some rare cases on which you could use both together. For instance, if you want the element to start hidden, then show up with a transition, and have another event linked to it that should fire only when the element is visible

    In the following example, there's a click event linked to the div element that will fire only when visible (so couldn't use just the opacity), but also have a transition when revealing (so couldn't use just visibility)

    $('button').click(function() {
    		$('.opacity').toggleClass("visible");
    });
    
    $('.opacity').click(function() {
    		alert("clicked");
    });
    div {
        width: 100vw;
        height: 100vh;
        transition: opacity 1s ease;
        background: chartreuse;
    }
    
    .visibility{
      visibility:hidden;
    }
    
    
    .opacity{
      visibility:hidden;
      opacity:0;
    }
    
    .visible{
      opacity:1;
      visibility: visible;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button>
    toggle
    </button>
    
    <div class="opacity"> opacity:0 </div>
    <hr>