How to center canvas in html5

后端 未结 9 1451
自闭症患者
自闭症患者 2020-12-12 11:02

I\'ve been searching for a solution for a while now, but haven\'t found anything. Maybe it\'s just my search terms. Well, I\'m trying to make the canvas center according to

9条回答
  •  攒了一身酷
    2020-12-12 11:30

    To center the canvas element horizontally, you must specify it as a block level and leave its left and right margin properties to the browser:

    canvas{
        margin-right: auto;
        margin-left: auto;
        display: block;
    }
    

    If you wanted to center it vertically, the canvas element needs to be absolutely positioned:

    canvas{
        position: absolute;
        top: 50%;
        transform: translate(0, -50%);              
    }
    

    If you wanted to center it horizontally and vertically, do:

    canvas{
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);               
    }
    

    For more info visit: https://www.w3.org/Style/Examples/007/center.en.html

提交回复
热议问题