【问题标题】:Centered div is getting cut off at the top?居中的 div 在顶部被切断了吗?
【发布时间】:2016-09-10 07:22:25
【问题描述】:

这是我正在处理的页面:http://en08-phx.stablehost.com/~news/test.html

这是我用来使 div 居中的代码:

div {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);  
  width: 70%;
  height: auto;
  padding: 20px;  
  background-color:rgba(255, 255, 255, 0.2);
  color: white;
  text-align: center;
  border-radius:5px;
  border:2px solid rgba(255, 255, 255, 0.5);
}

每当我缩小浏览器的宽度或使用手机时,页面顶部就会开始被截断。

无论浏览器宽度的大小如何,我都希望 div 居中。但是,如果浏览器的高度太小,我宁愿只在顶部/底部添加 10px 的边距并确保所有文本都显示出来。

我到底做错了什么?

【问题讨论】:

  • 这是因为您将 div 居中,无论设备的高度是多少,因此上部被截断。

标签: html css


【解决方案1】:
<br clear="all">

这对我有用。只需将其放在您的内容元素之前,例如 div。

【讨论】:

    【解决方案2】:

    这种定位技术(顶部 50% 减去 translateY -50%)的问题在于它会根据自身的高度进行自我对齐。当视口挤压容器比视口高时,它保持居中,顶部和底部被切断。如果你能够使用 flexbox,我推荐使用 flexbox (http://caniuse.com/#search=flex)。

    将您希望始终居中的容器包装在另一个容器中,例如 centered-wrapper 并应用 flexbox 使其居中:

    .centered-wrapper {
      display: flex;
      flex-direction: column;
      justify-content: center;
      min-height: 100%;
    }
    

    这里的最小高度非常重要。如果您的 div 没有拉伸到页面的高度,它将填充并居中其子级。如果是,那么它将继续扩展,避免您也遇到这种情况。如果您的框相对于整个页面的高度,那么您还需要设置页面的高度才能使其正常工作:

    html,
    body {
      height: 100%;
    }
    

    您不需要对居中的 div 进行任何居中,只需视觉样式即可。

    这里是它的一个示例:https://jsfiddle.net/vfc9n7p2/

    【讨论】:

      【解决方案3】:
         body {
          display: flex;
          flex-direction: column;
          justify-content: center;
         }
         div {
      /* position: absolute; */
      /* left: 50%; */
      /* top: 50%; */
      /* transform: translate(-50%, -50%); */
          width: 70%;
          height: auto;
          padding: 20px;
          background-color: rgba(255, 255, 255, 0.2);
          color: white;
          text-align: center;
          border-radius: 5px;
          border: 2px solid rgba(255, 255, 255, 0.5);
          margin: 0 auto;
         }
      

      这对你来说很好。

      【讨论】:

      • 这个答案在 Chrome 中确实有效,但在 FireFox 中,div 一直位于顶部...
      • 显示:-webkit-box;显示:-webkit-flex;显示:-ms-flexbox;显示:弯曲; -webkit-box-orient:垂直; -webkit-box-direction:正常; -webkit-flex-direction:列; -ms-flex-direction:列;弹性方向:列; -webkit-box-pack:中心; -webkit-justify-content:中心; -ms-flex-pack:中心; justify-content: center;
      • 尝试使用供应商前缀
      猜你喜欢
      • 2020-04-04
      • 2015-07-18
      • 1970-01-01
      • 1970-01-01
      • 2016-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-21
      相关资源
      最近更新 更多