Home > Software design >  Expand div to specific height depending on amount of text
Expand div to specific height depending on amount of text

Time:12-06

I have set the height of a div to a specific value I.E 60px. I want the height of the div to expand to 80px and 100px depending on the amount of text in the div. I have tried to do this a few ways but as of yet haven't found a solution.

Here is my code.

  HTML
       <div id="header">
                <div class="header-text">
                    <h3 class="card-title">Text goes here, Text goes here, Text goes here,  </h3>
                    <h6 id="support-text">supporting text</h6>
    
    
                </div>
                   
        CSS
        #header {
        height: 60px;
        width: 100%;
        background-color: #f4f6f8;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0px 20px;
        
    }
    
    Javascript
    
    function increase() {
        var text = parseInt(document.getElementById("header").style.height);
        if (text < 80) {
            document.getElementById("header").style.height = "60px";
        } else if (text == 80) {
            document.getElementById("header").style.height = "80px";
        } else if (text > 80){
            document.getElementById("header").style.height = "100px";
    }
    
    increase();

         

CodePudding user response:

<div id="test"></div>

<script>
    const div = document.querySelector('#test'),
        divHeight = div.offsetHeight;

    if (divHeight === 72) {
        div.style.height = '100px';
    }
</script>

variables and value are just placeholders, you can change it.

CodePudding user response:

parseInt(document.getElementById("header").style.height)

The style height of your element will be exactly whatever you set it to. For example "60px".

If you want to find the actual height of the div, instead of .style.height use .clientHeight.

If the text goes beyond the height of the div, you can use .scrollHeight to get the full height of the content.

  • Related