中心的div在顶部被切断?

时间:2016-05-14 00:22:28

标签: html css

以下是我正在处理的页面: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的边距,并确保显示所有文本。

我到底错在了什么?

3 个答案:

答案 0 :(得分:3)

这种定位技术的问题(前50%减去translateY -50%)是它根据自己的高度对齐自己。当视口捕获比视口高的容器时,它保持居中,顶部和底部被切断。如果您能够使用flexbox,我建议使用flexbox(http://caniuse.com/#search=flex)。

将您想要的容器包裹在另一个容器(例如居中包装器)中,并应用flexbox将其置于中心位置:

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

这里的最小高度非常重要。如果你的div没有延伸到页面的高度,那么它将填充并居中于它的孩子。如果是,那么它将继续扩展,避免你也拥有的场景。如果你的盒子与整个页面的高度是相对的,那么你还需要设置页面的高度才能使其工作:

html,
body {
  height: 100%;
}

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

以下是其中的示例:https://jsfiddle.net/vfc9n7p2/

答案 1 :(得分:0)

   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;
   }

这对你来说很好。

答案 2 :(得分:0)

<br clear="all">

这对我有用。只需将它放在像div这样的内容元素之前。