如何根据窗口高度使元素滚动或居中

时间:2018-07-23 15:30:41

标签: html css css3 flexbox

我在页面中间居中放置一个元素。如果页面缩小到小于元素的高度,我仍然需要显示元素的顶部而不是居中。我希望元素的容器是可滚动的。

.card-display {
  margin: auto;
  top: 50%;
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 300px;
  height: 400px;
  background-color: grey;
  border-radius: 10px;
}
<div class="card-display" >
  <div>
    always need top line visible (i.e., if there is enough container height to fit the grey element, it should be vertically centered, otherwise container have scrolling)
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

检查是否适合您: 包装卡显示器以应用Flex居中方式。 jsfiddle

.container {
  display:flex;
  align-items: center;
  justify-content: center;
  position:absolute;
  width: 100%;
  height: 100%;
}
.card-display {
  align-items:center;
  position:absolute;
  width: 300px;
  height: 400px;
  border-radius: 10px;
  background-color: gray
}
@media screen and (max-height:400px) {
 body {
   background-color: blue;
 }
 .container {
   align-items:baseline;
 }
}

html:

<div class="container">
 <div class="card-display">
  <div>
   always need top line visible
  </div>
 </div>
</div>