Border of parent div not binding to size of children

Viewed 130

I have a larger program I've been working on that has multiple elements within a div, including a canvas. The div's border always seems to extend over the size of its children, I've simplified the code here, and am wondering if anyone has a solution.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gap Test</title>
</head>

<body>
    <div id="d">
        <canvas id="c" height="400" width="600"></canvas>
    </div>
</body>

<style>
    #d {
        border: 3px solid black;
    }
    
    #c {
        background: blue;
    }
</style>

</html>

3 Answers

The canvas tag by default has a display of inline, you can get rid of that space by changing its display property to block in CSS

<style>
    canvas {
        display: block;
    }
    #d {
        border: 3px solid black;
    }
    
    #c {
        background: blue;
    }
</style>

Add vertical-align: bottom to canvas.

This is caused by the canvas being an inline element. As such, it is effectively considered a character. As such, it must follow the baseline rule, which is to leave a little space below the line in case of characters such as gjpqy which drop below the baseline. By setting the vertical-align to bottom, you are actually aligning the canvas to the bottom of the drop-down letters. So long as the canvas itself is taller than the line-height, you will have no problems. Should the canvas be shorter than the line-height, you will start seeing "ghost margins" above the canvas as it reserves room for bdfhklt, the taller letters. This can be fixed by adding a line-height: 1px rule

You also need to use position: absolute for placing the canvas block inside the div. As we know that canvas default property is inline so that div and canvas were getting overriding.

Below is the code for your answer.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Gap Test</title>
    <style>
        #d {
            border: 3px solid black;
            position: absolute;  /* by default position is static */
        }
        
        #c {
            background: blue;
            display: block; /* by default is inline */
        }
    </style>
</head>

<body>
    <div id="d" height="auto">
        <canvas id="c" height="400" width="600"></canvas>
    </div>
</body>

</html>

Related