JavaScript: setting main div tag height to zero which makes all the sub divs have a height of zero

I just want to use some css to make the height of a div 0 which also makes all the heights of the sub divs 0. I then want to call a javascript function which when clicked it makes the height of the main div 100%.

Here is the code that I have written:

HTML

<div class="menuTitle" id="ButtonsTopStyle" onclick="ButtonsTop">CONNECTING   RODS</div>
<div class="buttonsTop" >
    <img src="Images/ButtonA.gif" alt="ImageA" class="smallButtons" />
    <img src="Images/ButtonA.gif" alt="ImageA" class="smallButtons" />
    <img src="Images/ButtonA.gif" alt="ImageA" class="smallButtons" />
</div>

<div class="menuTitle" id="ButtonsBottomStyle" onclick="ButtonsBottom">CRANKSHAFTS</div>
<div class="buttonsBottom">
    <img src="Images/ButtonA.gif" alt="ImageA" class="smallButtons" />
    <img src="Images/ButtonA.gif" alt="ImageA" class="smallButtons" />
    <img src="Images/ButtonA.gif" alt="ImageA" class="smallButtons" />
</div>

CSS

.smallButtons {
    box-sizing: border-box;
    margin-left: 10px;
    height: 50px;
    width: 50px;
    margin-top: 15px;
    background-color: white;
}

.menuTitle {
    color: white;
    font-family: "Arial";
    text-align: center;
    font-size: 30px;
    padding-bottom: 30px;
    padding-top: 30px;
}

.buttonsTop {
    margin-left: 23px;
}

.buttonsBottom {
    height: 0;
    margin-left: 23px;
}

The css I have written doesnt make the height of the .buttonBottom zero they are still being displayed on the page. I don’t want them to be displayed on the page

JAVASCRIPT

function ButtonsBottom() {
    document.getElementById("ButtonsTopStyle").style.height = "0";
    document.getElementById("ButtonsBottomStyle").style.height = "100%";
}

function ButtonsTop() {
    document.getElementById("ButtonsBottomStyle").style.height = "0";
    document.getElementById("ButtonsTopStyle").style.height = "100%";
}

As you can see I want the buttonsBottom to not be visible on the page when it loads but when you click on the onclick="ButtonBottom" div it makes the height 100% and makes the onclick="ButtonsTop" div have a height of 0

Answer

Add an

overflow:hidden;

to your .buttonsBottom div

Your div is expanding in height to accommodate your content.

What I’d suggest is adding an additional class of

.hidden {
    height: 0;
    overflow: hidden;
 }

to your CSS and then modifying your JavaScript to add/remove this class as needed.

The other option would be to use display: none; and display: block; instead of height. Which would be my preferred method as long as you aren’t aiming for a transition effect on height when clicked.

Leave a Reply

Your email address will not be published. Required fields are marked *