首页 > 解决方案 > 如果在屏幕上垂直和水平居中,居中 DIV 的顶部会出现剪切问题

问题描述

有很多方法可以使 div 元素在屏幕上垂直和水平居中,但没有一种方法能解决我面临的问题。

需要解决的问题是,如果居中 div 的高度远大于屏幕高度,居中元素的 top 会被剪掉,这种情况下居中的 div 应该顶部对齐,并且应该显示垂直滚动条以供使用。换句话说,页面高度应该等于居中的 div 高度。

我想放置在屏幕中心的 div 中提供的数据是动态的,所以我不知道居中 div 的高度,但在大多数情况下,它的高度小于页面高度。

我想要类似 Gmail 登录页面的东西。

这是代码 https://jsfiddle.net/wxeecwuk/

div {
    width: 200px;
    height: 200px;
    background-color: green;
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    overflow: auto;
}
<div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</div>

标签: css

解决方案


像这样 ?

div {
  width: 200px;
  max-height: 100%;
  background-color: green;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  margin: auto;
  overflow: auto;
}
<div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</div>


推荐阅读