CSS: hide element but keep width (and not height)

josch picture josch · May 21, 2013 · Viewed 26.8k times · Source
  • display:none will completely hide an element as if it now had a width and height of zero
  • visibility:hidden on the other hand will hide an element but reserve a rectangle of the element's original width and height in the document.

Is there a way through pure CSS, to hide an element such that it takes up zero height but its original width? Setting its height to zero doesnt work because I dont know to which height to set the element to once I want to show it again.

Specifically I want to achieve the following:

#top ul        {take up zero height but original width}
#top:hover ul  {restore original dimensions}

Edit: solved! The idea is to set height:auto to restore the original height.

See here http://jsfiddle.net/yP59s/ for the full version or here the css:

ul {margin:0px}
#top {border:1px solid}
#top ul {height:0px;overflow:hidden}
#top:hover ul {height:auto;}

and the html:

<div id="top">
    <h1>foobar</h1>
    <ul>
        <li>foo</li>
        <li>bar</li>
    </ul>
</div>
blubber

Answer

Axel Amthor picture Axel Amthor · May 21, 2013
#top         { width: 300px; height:0px; max-height:0px; }
#top:hover   {height: auto; width: 300px; }

http://jsfiddle.net/G5cgY/