4

Possible Duplicate:
Best way to center a <div> on a page vertically and horizontally?

I have a canvas element, and I'd like it to be right in the very center of a page, both vertical and horizontal.

I'm a programmer, and I don't much about CSS. Can anybody help me with centering my canvas both vertically and horizontally?

Here's my current CSS code:

/* Set up canvas style */
#canvas {
  font-family: 'pixel';
  margin-left: auto;
  margin-right: auto;
  display: block;
  border: 1px solid black;
  cursor: none;
  outline: none;
}

It's already being centered horizontally, but not vertically, thank you in advance!

Community
  • 1
  • 1
David Gomes
  • 5,644
  • 16
  • 60
  • 103

2 Answers2

2

this should do the trick:

#canvas {
    position: absolute;
    top: 50%; left: 50%;
    width: 200px;
    height: 200px;
    margin: -100px 0 0 -100px;
}

The margin top and left has to be negative half the height and width of the element.

The same principal applies if you don't know the width and height and need to calculate it with javascript. Just get the width/height, divide those by half and set the values as a margin in the same way as the example above.

Hope that helps :)

will
  • 4,557
  • 6
  • 32
  • 33
  • That only works if the height of the element is known beforehand. If it is not until the time of rendering, there is no choice but to use JavaScript to get the height and then set the margin's inline. – Adam Jenkins May 01 '12 at 15:28
  • @Adam, i made it possible to do it purecss – Vladimir Starkov Jun 05 '12 at 04:52
  • No you didn't - just as I pointed out, you can only do it if you know the height of the element before hand. You set yours too 100px and, therefore, knew it. – Adam Jenkins Jun 05 '12 at 13:24
2

I don't know if this would help, but I wrote this jQuery plugin that might help. I also know this script needs adjustments. It'd adjust the page when needed.

(function($){
    $.fn.verticalCenter = function(){
        var element = this;

        $(element).ready(function(){
            changeCss();

            $(window).bind("resize", function(){
                changeCss();
            });

            function changeCss(){
                var elementHeight = element.height();
                var windowHeight = $(window).height();

                if(windowHeight > elementHeight)
                {
                    $(element).css({
                        "position" : 'absolute',
                        "top" : (windowHeight/2 - elementHeight/2) + "px",
                        "left" : 0 + "px",
                        'width' : '100%'
                    });
                }
            };
        });

    };
})(jQuery);


$("#canvas").verticalCenter();

Refined Code + Demo

Please, view this demo in "Full page" mode.

(function($) {
  $.fn.verticalCenter = function(watcher) {
    var $el = this;
    var $watcher = $(watcher);
    $el.ready(function() {
      _changeCss($el, $watcher);
      $watcher.bind("resize", function() {
        _changeCss($el, $watcher);
      });
    });
  };
  function _changeCss($self, $container) {
    var w = $self.width();
    var h = $self.height();
    var dw = $container.width();
    var dh = $container.height();
    if (dh > h) {
      $self.css({
        position: 'absolute',
        top: (dh / 2 - h / 2) + 'px',
        left: (dw / 2 - w / 2) + 'px',
        width: w
      });
    }
  }
})(jQuery);

$("#canvas").verticalCenter(window);

$(function() {
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
  drawSmile(ctx, 0.9, 'yellow', 'black', 0.75);
});

function drawSmile(ctx, scale, color1, color2, smilePercent) {
  var x = 0, y = 0;
  var radius = canvas.width / 2 * scale;
  var eyeRadius = radius * 0.12;
  var eyeXOffset = radius * 0.4;
  var eyeYOffset = radius * 0.33;
  ctx.save();
  ctx.translate(canvas.width / 2, canvas.height / 2);
  ctx.beginPath(); // Draw the face
  ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  ctx.fillStyle = color1;
  ctx.fill();
  ctx.lineWidth = radius * 0.05;
  ctx.strokeStyle = color2;
  ctx.stroke();
  ctx.beginPath(); // Draw the eyes
  ctx.arc(x - eyeXOffset, y - eyeYOffset, eyeRadius, 0, 2 * Math.PI, false);
  ctx.arc(x + eyeXOffset, y - eyeYOffset, eyeRadius, 0, 2 * Math.PI, false);
  ctx.fillStyle = color2;
  ctx.fill();
  ctx.beginPath(); // Draw the mouth
  ctx.arc(0, 0, radius * 0.67, Math.PI * (1 - smilePercent), Math.PI * smilePercent, false);
  ctx.stroke();
  ctx.restore();
}
#canvas {
  border: 3px dashed #AAA;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="canvas" width="256" height="256"></canvas>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
xivo
  • 2,054
  • 3
  • 22
  • 37