简体   繁体   中英

Get a <canvas> element to fill remaining height in a parent div?

I have a canvas, I want to show it under a piece of text. The parent div that contains both the text and the canvas has an explicit height of 200px. I want the canvas to just fill in whatever height is left over below the text div, something like:

----------------------------
|  label div               |
----------------------------
|                          |
|  canvas                  |  entire height of parent
|  fill in rest of height  |  div should be 200px.
|  (height = 100%)         |
|                          |
----------------------------

This is what I tried:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
   <head>
      <style type="text/css">
         html, body {
           margin: 0px;
           padding: 0px;
         }
         canvas {
           width:50px;
           height:100%;
         }
      </style>
   </head>
   <body>
      <div style="background-color: rgb(255, 200, 0); width:100%; height: 200px;">
         <div>hello</div>
         <canvas style="background-color: rgb(0,255,128);">
         </canvas>
      </div>
   </body>
</html>

But notice how the canvas element spills over the bottom of the parent div:

在此处输入图片说明

Is there a way to just get the canvas to fill the remaining space without spilling out?

Thank you

You can make a label class for the div above the container and give it a height percent and set the canvas to the remaining height. I've done an example with your code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
   <head>
      <style type="text/css">
         html, body {
           margin: 0px;
           padding: 0px;
         }
         canvas {
           width:50px;
           height:90%;
         }
         .label {
        height: 10%;
         }
      </style>
   </head>
   <body>
      <div style="background-color: rgb(255, 200, 0); width:100%; height: 200px;">
         <div class="label">hello</div>
         <canvas style="background-color: rgb(0,255,128);">
         </canvas>
      </div>
   </body>
</html>

Maybe try something like this:

 ... 
 <div style="background-color: rgb(255, 200, 0); width:100%; height: 200px; overflow: hidden">
 ...

Notice the added css rule overflow:hidden

Here is the full usage documentation for the css rule overflow http://www.w3.org/TR/CSS21/visufx.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