父项 div 的边框未绑定到子项的大小

Border of parent div not binding to size of children

我有一个我一直在研究的更大的程序,它在 div 中有多个元素,包括 canvas。 div 的边框似乎总是超出其子项的大小,我在这里简化了代码,想知道是否有人有解决方案。

<!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>

canvas 标签默认显示为内联,您可以通过将其显示 属性 更改为 CSS[= 中的块来摆脱 space 11=]

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

vertical-align: bottom 添加到 canvas。

这是因为 canvas 是内联元素。因此,它实际上被视为一个角色。因此,它必须遵循基线规则,即在诸如 gjpqy 之类的字符低于基线的情况下,在线下方留一点 space 。通过将 vertical-align 设置为底部,您实际上是将 canvas 对齐到 drop-down 字母的底部。只要 canvas 本身比 line-height 高,就没有问题。如果 canvas 比 line-height 短,您将开始在 canvas 上方看到“重影边距”,因为它为 bdfhklt(较高的字母)保留了空间。这可以通过添加 line-height: 1px 规则

来解决

您还需要使用 position: absolute 将 canvas 块放置在 div 内。我们知道 canvas 默认 属性 是内联的,因此 divcanvas 被覆盖。

下面是您的答案代码。

<!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>