Percentage Height HTML 5/CSS

Viewed 258796

I am trying to set a <div> to a certain percentage height in CSS, but it just remains the same size as the content inside it. When I remove the HTML 5 <!DOCTYTPE html> however, it works, the <div> taking up the whole page as desired. I want the page to validate, so what should I do?

I have this CSS on the <div>, which has an ID of page:

#page {
    padding: 10px;
    background-color: white;
    height: 90% !important;
}
7 Answers

In order to use percentage(%), you must define the % of its parent element. If you use body{height: 100%} it will not work because its parent have no percentage in height. In that case in order to work that body height you must add this in html{height:100%}

In other cases to get rid of that defining parent percentage you can use

body{height:100vh}

vh stands for viewport height

You can use 100vw / 100vh. CSS3 gives us viewport-relative units. 100vw means 100% of the viewport width. 100vh; 100% of the height.

    <div style="display:flex; justify-content: space-between;background-color: lightyellow; width:100%; height:85vh">
        <div style="width:70%; height: 100%; border: 2px dashed red"></div>
        <div style="width:30%; height: 100%; border: 2px dashed red"></div>
    </div>

Sometimes, you may want to conditionally set the height of a div, such as when the entire content is less than the height of the screen. Setting all parent elements to 100% will cut off content when it is longer than the screen size.

So, the way to get around this is to set the min-height:

Continue to let the parent elements automatically adjust their height Then in your main div, subtract the pixel sizes of the header and footer div from 100vh (viewport units). In css, something like:

min-height: calc(100vh - 246px);

100vh is full length of the screen, minus the surrounding divs. By setting min-height and not height, content longer than screen will continue to flow, instead of getting cut off.

With new CSS sizing properties you can get away with not setting exact height on parent. The new block-size and inline-size properties can be used like this:

<!DOCTYPE html>
<style>
  #parent {
    border: 1px dotted gray;
    height: auto;   /* auto values */
    width: auto;
  }

  #wrapper {
    background-color: violet;
    writing-mode: vertical-lr;
    block-size: 30%;
    inline-size: 70%;
  }

  #child {
    background-color: wheat;
    writing-mode: horizontal-tb;
    width: 30%;  /* set to 100% if you don't want to expose wrapper */
    height: 70%; /* none of the parent has exact height set */
  }
</style>

<body>
  <div id=parent>
    <div id=wrapper>
      <div id=child>Lorem ipsum dollar...</div>

Resize the browser window in full page mode. I think the values are relative to viewport height and width.

For more info refer: https://www.w3.org/TR/css-sizing-3/
Almost all browsers support it: https://caniuse.com/?search=inline-size

Related