jquery - 将比视口(viewport)宽的 DIV 居中

标签 jquery html css

<分区>

我正在创建一个页面来显示祖先的家谱。
该页面是动态创建的,所以我无法知道会有多少代或内容是什么。
然而,此处显示了一个相当简单的示例:http://myrootsmap.com/so_tree2.php .

就目前而言,它非常简单,因为它适合任何普通的浏览器窗口(我暂时不支持移动设备)。
然而,随着每一代的增加,树的宽度都会加倍,因此当表格对于视口(viewport)来说太大时,我需要进行良好的展示。
如果您缩小浏览器窗口的大小,您将看到:

  1. 树在需要时有自己的水平滚动条(好)
  2. 树总是左对齐(不好)
  3. 如果树对于视口(viewport)来说太高,则垂直滚动条在窗口上而不是树上(同样不好)

总而言之,我的 HTML 如下所示:

<div id="container">
  <?php include( "includes/header_index.php"); ?>

  <div id="wholetree">
    <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" name="add_gen">
      <input type="hidden" name="MM_insert" value="add_gen">
      <a href="javascript:void()" onclick="document.add_gen.submit()" class="tree_button">Add Another Generation</a>
    </form>
    <form action="map.php" method="get" name="view_map">
      <input type="hidden" name="origin" value="<?php echo $origin_id ?>">
      <a href="javascript:void()" onclick="document.view_map.submit()" class="tree_button view_button">View the Map</a>
    </form>
    <div class="tree">
      <?php include($tree); ?>
    </div>
  </div>
</div>

和 CSS

* {
  margin: 0;
  padding: 0;
}
#container {
  display: flex;
  min-height: 100%;
  flex-direction: column;
}
#wholetree {
  position: relative;
  top: 120px
}
.tree {
  overflow: auto;
  padding: 10px
}
.tree ul {
  padding: 0 0 20px;
  position: relative;
}
.tree li {
  display: inline-block;
  white-space: nowrap;
  vertical-align: bottom;
  margin: 0 -2px 0 -2px;
  text-align: center;
  list-style-type: none;
  position: relative;
  padding: 0 5px 20px 5px;
}

问题:

  • 如何让 div class=tree 位于 div id=wholetree 的中心?
  • 如果 div class=tree 溢出,如何滚动到底部?和
  • 如何在其上设置垂直滚动条?

我只喜欢 CSS,但如果这是唯一的方式,我会使用 jQuery。

最佳答案

您可以将您想要水平居中的元素定位在您的相对父元素中并执行以下操作:

.tree{
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

这将首先将元素向右对齐 50%,然后将其平移回其自身宽度的 50%。

它(令人惊讶地)对浏览器也非常安全。

关于jquery - 将比视口(viewport)宽的 DIV 居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39730749/

相关文章:

html - 导航菜单不显示

css - 与 css 转换相关的 <button> 元素上的 chrome 中的模糊文本?

javascript - javascript 中的照片库

javascript - 计数器不停止,SetInterval

用于动画线性渐变的 jQuery 脚本

html - Safari 中的 Flexbox 行换行问题

javascript - jQuery AJAX : Returns request. 成功后失败

html - 为什么位置:absolute adds 4px to the height of the outer container and how to remove it?

css - 如何连续放置内容并防止 react native 溢出?

html - CSS - 如何更改 rtl 方向页面中复选框输入的位置