HTML - 如何在html5中居中画布
我现在一直在寻找解决方案,但还没找到任何东西。 也许它只是我的搜索条件。好吧,我试图根据浏览器窗口的大小制作画布中心。 画布是800x600。如果窗口低于800x600,它也应该调整大小(但目前不是很重要)
8个解决方案
152 votes
为画布提供以下css样式属性:
canvas {
padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
display: block;
width: 800px;
}
编辑
由于这个答案很受欢迎,让我补充一点细节。
上面的属性将水平居中画布,div或您拥有的任何其他节点相对于它的父节点。 无需更改顶部或底部边距和填充。 您指定宽度并让浏览器使用自动边距填充剩余空间。
但是,如果你想输入更少,你可以使用你想要的任何css速记属性,例如
canvas {
padding: 0;
margin: auto;
display: block;
width: 800px;
}
垂直居中画布需要采用不同的方法。 您需要使用绝对定位,并指定宽度和高度。 然后将left,right,top和bottom属性设置为0,让浏览器使用自动边距填充剩余空间。
canvas {
padding: 0;
margin: auto;
display: block;
width: 800px;
height: 600px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
画布将根据position设置为display: flex或absolute的第一个父元素居中,如果未找到,则为居中。
另一种方法是使用IE11中提供的display: flex
另外,请确保使用最近的doctype,例如xhtml或html 5。
Marco Luglio answered 2019-08-12T09:02:52Z
44 votes
您可以为画布提供ff CSS属性:
#myCanvas
{
display: block;
margin: 0 auto;
}
jinmichaelr answered 2019-08-12T09:03:16Z
20 votes
只需将HTML居中于HTML:
#test {
width: 100px;
height:100px;
margin: 0px auto;
border: 1px solid red;
}
只需将高度和宽度更改为任何内容,您就可以获得居中的div
[http://jsfiddle.net/BVghc/2/]
JoeCianflone answered 2019-08-12T09:03:54Z
5 votes
只有当您的画布与容器的宽度相同时,上述答案才有效。
这适用于:
SystemicPlural answered 2019-08-12T09:04:35Z
2 votes
我有同样的问题,因为我有许多不同宽度的图片,我只加载高度信息。 设置宽度允许浏览器拉伸和挤压图片。 我通过在image_tag线居中之前使文本行解决问题(也摆脱了float:left;)。 我本来希望文本保持一致,但这是一个小小的不一致,我可以容忍。
MDM answered 2019-08-12T09:05:01Z
2 votes
使用此代码:
.text-center{
text-align:center;
margin-left:auto;
margin-right:auto;
}
Your browser does not support the HTML5 canvas tag.
Keyur Patel answered 2019-08-12T09:05:21Z
1 votes
要水平居中canvas元素,必须将其指定为块级别,并将其左右边距属性保留给浏览器:
canvas{
margin-right: auto;
margin-left: auto;
display: block;
}
如果你想垂直居中,那么canvas元素必须绝对定位:
canvas{
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
如果您想水平和垂直居中,请执行以下操作:
canvas{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
欲了解更多信息,请访问:[https://www.w3.org/Style/Examples/007/center.en.html]
Konkret answered 2019-08-12T09:06:07Z
0 votes
将text-align: center;添加到了父标签.那就是它。
例:
Raj Yadav answered 2019-08-12T09:06:36Z