pedrotech
pedrotech

Reputation: 1379

Hold parent height after child element is toggled with pure CSS

I need to hold parent height after a child element is toggled.
The parent is a bootstrap panel. #big-menu is the child element.
div.content is the element which can modify its height.
I already have a javascript 'solution' (see resizeContent function).
I would to know if there is a CSS solution.

Plunker: http://plnkr.co/edit/tDYZ5YeppCtOgShw97Em
JSFiddle: https://jsfiddle.net/pedrobad/p2b3uufd/

<!doctype html>
</html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> 
</script>
<script type="text/javascript">
    var opened = false;
    function action() {
        var hBefore = $('.panel').height();
        if (opened){
            $('#big-menu').hide()
        } else {
            $('#big-menu').show();
        }
        opened = !opened;
        resizeContent(); // comment this line to see my issue
        var hAfter = $('.panel').height();
        $('#big-menu').html('BIG MENU <br/>hBefore: ' +  hBefore + ' hAfter: ' + hAfter);
    }
    function resizeContent() {
        if (opened){
            $('.content').height(250); // 300 - 50
        } else {
            $('.content').height(300);
        }
    }
</script>
</head>
<body>
<div class='panel'>
    <div class='panel-heading'><h2>Heading</h2></div>
    <div class='panel-body'>
        <div class='content' style="overflow-y: scroll; height: 300px; background-color: grey;">
        <ul>
            <li>foo</li><li>foo</li><li>foo</li><li>foo</li><li>foo</li>
            <li>foo</li><li>foo</li><li>foo</li><li>foo</li><li>foo</li>
            <li>foo</li><li>foo</li><li>foo</li><li>foo</li><li>foo</li>
            <li>foo</li><li>foo</li><li>foo</li><li>foo</li><li>foo</li>
            <li>foo</li><li>foo</li><li>foo</li><li>foo</li><li>foo</li>
            <li>LAST ITEM</li>
        </ul>
    </div>
</div>
<div class='panel-footer'>
    <div id='big-menu' style="height: 50px; display: none">MENU</div>
    <button onclick='action()'>Show</button>
</div>
</div>
</body>
</html>

Upvotes: 1

Views: 82

Answers (1)

Andrew
Andrew

Reputation: 39

I don't totally understand what you're trying to achieve, but if you want a hidden element to still take up space inside its parent you can use visibility: hidden instead of display: none.

In JS you would need to add a class, for example 'visuallyhidden', to the element you want hide. Then apply styles to that class in CSS like:

.visuallyhidden {
    visibility: hidden;
}

Upvotes: 1

Related Questions