css - canvas与块级元素
天蓬老师
天蓬老师 2017-04-17 13:55:00
0
1
579

这两天在看canvas,资料说canvas是块级元素。然后有个事情就让我很费解。。。

有简单的 html文件如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
<canvas id="a" style="border: 1px solid #000;">
    不支持canvas!
</canvas>
</body>
</html>

有这样两个小知识点:canvas 如果不设置宽高,默认 300*150.而拥有定宽的块元素想在所在行实现水平居中,只要设置css属性margin: 0 auto;就可以了。

但是,我给这个标签加了 margin 属性,它并没有水平居中。

我觉得可能是因为默认的 300*150 是画布内容的宽高,想达到效果要设置画布的大小。然后我在行内样式又追加了canvas的宽高~还是不能实现水平居中。

想让它水平居中,必须要设置display: block

可是,canvas 如果是块级元素的话,它的 display 属性难道不应该默认就是 block 吗?十分费解。也不知道是只有 canvas 这样还是其他的“块级”元素也有这样的表现。。有了解的朋友可以帮忙解答一下吗?谢谢。

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(1)
小葫芦

Canvas is an inline element and an inline replacement element.

In Chrome, when display is not set, the font color is lighter. And its default attribute is inline. So it is not a block-level element, and the data is wrong.
As for why the information is wrong, I think it’s because he doesn’t understand that there is another element in CSS called replacement elements. Generally, inline elements cannot set height and width, but inline replacement elements can.
So canvas is an inline replaceable element. For inline replaceable elements, when margin-left and margin-right are set to auto, their value is 0.
So you have the situation above. Its calculation is different from that of block-level replaceable elements. When margin-left and margin-right of block-level replaceable elements are set to auto, their values ​​will be equal, so they will be horizontally centered.
(If you are interested, you can follow the public account: Programming Talk, which contains knowledge about CSS.)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!