将Javascript输出垂直对齐设置为中间?

时间:2015-01-29 15:58:29

标签: javascript html css vertical-alignment

我有一个Javascript时钟显示在一个瘦框:

http://i.imgur.com/kyoZ5c8.png

<!DOCTYPE html>
<HTML>
<HEAD>
  <TITLE>Untitled</TITLE>
  <SCRIPT>
      function checkTime(i) {
        if (i < 10) {
            i = "0" + i;
        }
        return i;
      }
      function startTime() {
        var today = new Date();
        var h = today.getHours();
        var m = today.getMinutes();
        var s = today.getSeconds();
        // add a zero in front of numbers<10
        m = checkTime(m);
        s = checkTime(s);
        document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
        t = setTimeout(function () {
            startTime()
        }, 500);
      }
  </SCRIPT>
</HEAD>
<BODY onload="startTime()">
  <DIV id="time" style="width: 95px; height: 32px; border: solid; border-width: thin; text-align: center; vertical-align: middle"><p>time</p></DIV>
</BODY>
</HTML>

不幸的是,我无法将帧内的垂直对齐方式设置为MIDDLE,尽管我设置了vertical-align: middle

那么我怎样才能将它垂直居中?

3 个答案:

答案 0 :(得分:5)

vertical-align属性适用于内联级别和表格单元格;默认情况下,div的{​​{1}}属性为display,因此忽略block属性。

使用vertical-align(与line-height: 32px相同)。

&#13;
&#13;
height
&#13;
function checkTime(i) {
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}

function startTime() {
  var today = new Date();
  var h = today.getHours();
  var m = today.getMinutes();
  var s = today.getSeconds();
  // add a zero in front of numbers<10
  m = checkTime(m);
  s = checkTime(s);
  document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
  t = setTimeout(function() {
    startTime()
  }, 500);
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以尝试line-height属性:

line-height: 32px;

function checkTime(i) {
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}
function startTime() {
  var today = new Date();
  var h = today.getHours();
  var m = today.getMinutes();
  var s = today.getSeconds();
  // add a zero in front of numbers<10
  m = checkTime(m);
  s = checkTime(s);
  document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
  t = setTimeout(function () {
    startTime()
  }, 500);
}
startTime();
<DIV id="time" style="width: 95px; height: 32px; border: solid; border-width: thin; text-align: center; line-height: 32px;"><p>time</p></DIV>

答案 2 :(得分:1)

可能是最简单的解决方案:使用line-height: 32px;。这将使行本身与框一样高,文本将根据字体或多或少地居中。