soystuff
soystuff

Reputation: 23

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?

Upvotes: 1

Views: 1103

Answers (3)

Samuel Reid
Samuel Reid

Reputation: 1766

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.

Upvotes: 1

apsillers
apsillers

Reputation: 115970

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>.

Upvotes: 3

Euphe
Euphe

Reputation: 3709

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.

Upvotes: 0

Related Questions