简体   繁体   中英

Setting min-height automatically with jQuery or Javascript

I would like to use a script to add min-height or max-height to an element based on the height of the actual element.

So I'm getting the.height() (?) of a div and then using that value to set a min/max-height. Is this possible? It has to be dynamical, so that the div can change height but still have the right min-height or max-height.

I haven't tried anything, only searched for how to do it - I'm really not an expert on jQuery og Javascript. The thing I'm doing now is using console.log to give me the height of an element (a hero section for example) so that I don't need to manually check it in developer. And then I write the value as a min-height in CSS. The reason I'm doing it is because of the new Lighthouse Core Web Vitals (Cumulative Layout Shift (CLS)).

EDIT: So I think I found a solution, and (like I said) I'm not an expert here, but any feedback is very much appreciated.

jQuery(".hero").css("min-height", function(){ 
  return jQuery(".hero").height();
});

this is an example of what you want

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Set a DIV height</title>
<style>
    .box{
        background: #f2f2f2;
        border: 1px solid #ccc;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){

        var newHeight = $(".input-height").val();
        $(".box").height(newHeight);

});
</script>
</head> 
<body>
    <form>
        <input type="text" class="input-height">
        <button type="button" class="set-height-btn">Set Height</button>
        <p>Enter the value in input box either as number (e.g. 100, 200) or combination of number and unit (e.g. 100%, 200px, 50em, auto) and click the "Set Height" button.</p>
    </form>
    <br>
    <div class="box">This is simple DIV box</div>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM