【问题标题】:How to make element scroll or center depending on window height [duplicate]如何根据窗口高度使元素滚动或居中
【发布时间】:2018-12-31 02:53:21
【问题描述】:

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

.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>

【问题讨论】:

  • 这是一个使用您的代码的示例:jsfiddle.net/Lycz3ngp
  • Flexbox 解决的另一个问题.. 非常简单。这是答案,但我如何标记为答案并关闭它?
  • 它被当作骗子关闭,因此无需标记。小提琴只是我帮助您快速更新您的代码。

标签: html css flexbox


【解决方案1】:

检查它是否适合您: 包装 card-display 以应用 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>

【讨论】:

  • 请在此处提供除了显示结果的 jsfiddle 之外提供解决方案的最少代码。
猜你喜欢
  • 1970-01-01
  • 2015-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 2012-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多