【问题标题】:Resize issue with table centered horizontally and vertically调整表格水平和垂直居中的问题
【发布时间】:2013-12-29 13:18:04
【问题描述】:

简单代码

<table class="box" border="1px">
  <tr>
    <td valign="top">
      my content
    </td>
  </tr>
</table>

风格

.box {
    width:300px;
    height:300px;
    background-color:#d9d9d9;
    position:absolute;
    margin-left:-150px;
    /* half of width */
    margin-top:-150px;
    /* half of height */
    top:50%;
    left:50%;
}

(见this fiddle

允许水平和垂直居中表格。但是,当窗口大小调整为小于表格时,即使显示滚动条,我也无法看到内容的顶部。为什么?

【问题讨论】:

  • 因为负上边距?
  • 尝试使用 % 而不是 px,这会给你的盒子一个响应式元素
  • @onetrickpony, @Beep :: 不,这些都不能解决这个问题...

标签: html css


【解决方案1】:

为您的文档指定一个最小高度:

html{
  position:relative;
  height: 100%;
  min-height: 300px;
}

这样窗口的高度永远不会小于框。

(需要height:100% 以使您的框居中)


...即使显示滚动条,

您看到滚动条是因为有内容溢出,但 html 的高度不包括额外的空间(当应用负边距时,它不考虑额外的高度)

【讨论】:

  • 为什么需要position:relative; for html
  • 你的盒子是绝对定位的,看起来你希望它在窗口中居中。所以必须定位窗口元素。我认为这是默认设置,并且没有必要这样做,但事实并非如此。
  • 你的盒子缺少定位的祖先可能是你得到这种行为的原因
【解决方案2】:
.box {
    width:50%;
    height:50%;
    background-color:#d9d9d9;
    position:absolute;
    top:25%;
    left:25%;
}

【讨论】:

  • 盒子必须有固定大小(在我的情况下它实际上是一张图片),所以这不是我的解决方案。
  • OneTrickPony 的方法可以做到。
【解决方案3】:
.box {
    width:50%;
    height:50%;
    background-color:#d9d9d9;
    position:absolute;
    margin-left:-150px;
    /* half of width */
    margin-top:-150px;
    /* half of height */
    top:50%;
    left:50%;
}

.top {

    margin-left:2cm;
    margin-right:2cm;
    vertical-align:text-top;
}


html

<table class="box" border="1px">
  <tr>
    <td class="top">my content</td>
  </tr>

【讨论】:

  • 只要有负边距,看不到顶部的问题就会一直存在。
猜你喜欢
  • 2011-04-19
  • 1970-01-01
  • 2020-05-28
  • 2019-07-19
  • 2015-08-29
相关资源
最近更新 更多