Flomp Flomp - 1 month ago 14
CSS Question

Div Scaling in Multi-Level Dropdown

i am trying to scale a div Container in a dropdown menu, so that it fits the text inside better.

<div class='dropdown'>
<button class ="dropbtn"><b>Hover!</b></button>
<div class='dropdown-content'>
<div class='dropdown-level2'>
<button class ="dropbtn-level2"><b>"..."</b></button>
<div class='dropdown-content-level2'>
<a>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</a>
</div>
</div>
</div>
</div>


See: http://codepen.io/anon/pen/BLvxwY

Of course i could just set a min-width, however the content is dynamically generated. Thus a text shorter than the min-width can occur.

How can i scale the div accordingly?

Thanks

Answer

You can use Js and count your text length.

After that change the container width with If, Else if and Else statement.

Its look like this:

$(document).ready(function(){

  $('.dropdown-content-level2 > a').each(function(){

    //count your text length
    var textLength = $(this).html().length;

    //if it less from 100 characters
    if (textLength < 100) {

      $(this).css('width', '100px')

    } else {

      $(this).css('width', '200px')

    }

  })

})

And if you have more situations:

$(document).ready(function(){

  $('.dropdown-content-level2 > a').each(function(){

    var textLength = $(this).html().length;

    if (textLength < 100) {

      $(this).css('width', '100px')

    } else if (textLength > 100 && textLength < 200) {

      $(this).css('width', '200px')

    } else {

      $(this).css('width', '300px')

    }

  })

})

Working CodePen

Comments