Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a div a percentage of the overall body height?

I'm trying a more fluid design.

I want specific divs to be a percentage of the overall body. I also want to set fluid / liquid padding within each div.

<body>
   <div class='image'></div>
   <div class='fourty'></div>
   <div class='sixty'></div>
</body>

CSS:

body {
 margin-top: 85px;
 min-height: 100%;
}

.image {
  content: image_url('something.jpg');
  width: 100%;
  height: auto;
}

/*I'm assuming the padding I'm setting is a percentage of the .fourty
  div not the overall body. Granted, width is 100%.*/
.fourty{
  padding: 4% 8%;
  min-height: 40%;
  width: 100%;
}

.sixty{
  padding: 4% 8%;
  min-height: 60%;
  width: 100%;
 }

The problem I'm having is that the percentage height does not seem to take effect for these divs. It seems to just be an auto height based off the contents of the div.

How do I correct / achieve this? I'm open to a JS solution, but would be more interested as to how to accomplish this in CSS.

like image 895
someoneHere Avatar asked Nov 02 '25 07:11

someoneHere


1 Answers

As far as CSS goes, there are no styles that you can apply to make an element's height equal to a certain percentage of the total document (body) height.

CSS does, however, offer you options to style an element's heights to a certain percentage of the viewport height (using VH units), but since this does not achieve your goal, I'll leave you with a javascript answer that does.

Relevant javascript functions:

function getDocumentHeight() {
  return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.documentElement.clientHeight);
};

function setDivHeight(target, percentage) {
    var desiredHeight = getDocumentHeight() * (percentage/100)
    target.style.height = desiredHeight + 'px';
};

To set the height initially and on viewport resizes:

var targetDiv = document.getElementById('target');

setDivHeight(targetDiv);

window.addEventListener('resize', setDivHeight.bind(null, targetDiv))
like image 196
AJeezy9 Avatar answered Nov 03 '25 22:11

AJeezy9



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!