-1

How to add style only under certain conditions?

I'm working on a div that has a max-height and content keeps getting added to it. The div grows as more content gets added but when it reaches the max height, it stops growing and acquires a scroll bar.

At that point, I'd like to add a border to the div to give the impression that the content continues below the bottom border.

Here is a very simplified version of the code:

<html>
<head>

<style>
    .will-get-border {
        /* border: 1px solid black; // <-- only if height >= 100px */
        max-height: 100px;
        overflow: auto;
    }
</style>

<script>
    function AddListItem() {
        var ul = document.getElementById('unorderedList');
        var li = document.createElement('li');
        li.innerHTML = 'This is a list item.';
        ul.appendChild(li);
    }
</script>

</head>
<body>

<div class="will-get-border">
    <ul id="unorderedList"></ul>
</div>

<input type="button" onclick="AddListItem()" value="Add list item" />
</body>
</html>

Would I need SASS or LESS for something like this?

Matt Komarnicki
  • 5,198
  • 7
  • 40
  • 92
gib65
  • 1,709
  • 3
  • 24
  • 58
  • What height? If it's element height then you could use script, if it was media then you can use [media query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries). – Shinjo Jun 26 '19 at 02:14
  • if the list items are always a fixed height and there is a max height on the containing div, you can just do the math and figure out how many items it takes to get to that overflow point and dynamically add a class that has a border with something like `element.classList.add("mystyle");` – Yeysides Jun 26 '19 at 02:28

1 Answers1

0

You should handle this with JavaScript! The process is so simple, the scenario is like that when you want to add elements to you need to add a condition like:

if(el.count > 5) { // also you can get the parent element and check the `max-height` property of it
  // do some stuff, in your case set the max height to the parent element like
  const parent = document.querySelector('.parentEl')
  parent.style.maxHeight = yourMaxHeihgtValue
}

Or you can check element maxheight if it was larger than your target threshold like below:

const parent = document.querySelector('.parentEl')
const targetMaxHeight = parent.style.maxHeight

if( targetMaxHeight >= thresholdValue ) {
   // set the parent max height to the threshold value
   parent.style.maxHeight = yourMaxHeihgtValue
}

Please note that you have to run this code on every add by wrapping it into a function and calling it inside your AddListItem function.

halfer
  • 19,824
  • 17
  • 99
  • 186
amdev
  • 6,703
  • 6
  • 42
  • 64