消除 HTML5 画布元素下方的幽灵边距?

2022-01-17 00:00:00 html css html5-canvas

当我们创建 HTML5 画布元素时,即使我们将边距和内边距设置为 0,画布元素下方也会出现幻影边距.

When we create an HTML5 canvas element, a ghost margin appears below the canvas element even though we set the margin and padding to 0.

示例:http://jsfiddle.net/yvbmd/

我们尝试了各种方法,但无法擦除鬼边.

We tried a variety of things, but can't erase the ghost margin.

我们如何创建没有幽灵边距的画布元素?

How can we create the canvas element without that ghost margin?

推荐答案

添加vertical-align: bottom.

这是由于画布是内联元素造成的.因此,它实际上被视为一个角色.因此,它必须遵循基线规则,即在 gjpqy 等字符低于基线的情况下,在行下方留出一点空间.通过将 vertical-align 设置为 bottom,实际上是将画布与下拉字母的底部对齐.只要画布本身高于line-height,就没有问题.如果画布比 line-height 短,您将开始在画布上方看到幽灵边距",因为它为 bdfhklt(较高的字母)保留了空间.这可以通过添加 line-height: 1px 规则来解决.

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.

相关文章