简体   繁体   中英

How do I center two canvases on top of one another?

I need to display one HTML5 canvas on top of another. This I have already managed in the following manner:

<canvas id="lower" width="900" height="550" style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="upper" width="900" height="550" style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>

However, I can't seem to figure out how to CENTER these two canvases while keeping one on top of the other. Any ideas?

Put them inside of a <div> with the styling:

div#canvasContainerId {
    position: relative;
    margin-left: auto;
    margin-right: auto;
    width: 900px;
}
  • The position: relative causes the absolute positioning of the <canvas> es to become relative to their containing <div> .
  • The auto margins, along with a fixed width , center the <div> .

Make an outer container with text-align:center and position:relative , make an inner container with position:relative , put the canvases inside the inner container, remove left:0;top:0; on both canvases, and remove the position:absolute on the lower of the canvases. And make sure in the html that the lower canvas comes before the upper canvas, like you have.

#container {
  text-align:center;
  position:relative;
}

#inner_container{
  position:relative;
}
#upper {
  z-index: 1;
}
#lower {
  position:absolute; z-index: 0;
}

http://jsfiddle.net/NW6Fx/

Edit : I believe the z-index property isn't needed if you do it this way. The order is just a matter of which canvas comes first in the html and which is position:relative .

You can put a breakline between them <br/>

or

Might try to give each of them the following css:

{
    margin:auto;
    clear:both;
}

With absolute positioning you should use top. For the first one, for example, put top: 50px . That will move the first elements 50px away from the top. For the second one, put top: 100px .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM