垂直和水平居中

4
我是一名程序员,不太懂CSS。我有一个canvas元素,希望它在页面上垂直和水平居中。请问有谁能帮我实现这个需求?
以下是当前的CSS代码:

可能重复:
最佳方式居中一个<div>,包括垂直方向和水平方向?

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

它已经水平居中,但垂直方向不居中,提前致谢!


请问您能否提供更多的代码(HTML)? - Idrizi.A
没有通用的方法。如果您知道项目和父级的高度,可以进行计算。我认为CSS已经失败了。即使是CSS 3也无法处理简单的布局要求。 - stefan bachert
如果您的元素高度不会改变,那么这非常容易。(这是一个问题!) - Roko C. Buljan
我使用纯CSS完成了它,解决方案不依赖于块的大小。 - Vladimir Starkov
2个回答

2
这应该就可以解决问题了:
#canvas {
    position: absolute;
    top: 50%; left: 50%;
    width: 200px;
    height: 200px;
    margin: -100px 0 0 -100px;
}
元素的 margin-top 和 margin-left 值应该为其高度和宽度的负一半。
如果不知道元素的宽度和高度,需要使用 JavaScript 计算,同样适用上述原则。只需获取宽度/高度,除以二,并像上面的示例一样将值设置为 margin 即可。
希望这能帮到您 :)

只有在元素的高度预先知道的情况下才有效。如果直到渲染时才知道高度,那就别无选择,只能使用JavaScript来获取高度,然后设置边距的内联样式。 - Adam Jenkins
@Adam,我已经成功实现了使用纯CSS的方法。 - Vladimir Starkov
不,你没有 - 正如我所指出的,只有在事先知道元素的高度时才能这样做。你将你的设置为100像素,因此知道它的高度。 - Adam Jenkins

2

我不知道这是否有帮助,但我写了这个jQuery插件可能会有所帮助。我也知道这个脚本需要进行调整。它将在需要时调整页面。

(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();

精细化的代码+演示

请在"全屏模式"下查看此演示。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接